烟花粒子特效代码html
时间: 2023-09-10 17:10:58 浏览: 126
以下是一个基于HTML5 Canvas的烟花粒子特效代码,你可以在网页上运行它:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>烟花粒子特效</title>
<style type="text/css">
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="fireworks" width="800" height="600"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('fireworks');
var ctx = canvas.getContext('2d');
var particles = [];
var maxParticles = 50;
var hue = 120;
function Particle(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.color = 'hsl('+hue+', 100%, 50%)';
this.alpha = 1;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.fill();
ctx.closePath();
};
Particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
this.alpha -= 0.01;
this.radius -= 0.01;
};
function createParticles(x, y) {
for(var i = 0; i < maxParticles; i++) {
particles.push(new Particle(x, y, Math.random() * 4 + 1));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < particles.length; i++) {
particles[i].draw();
particles[i].update();
if(particles[i].alpha <= 0) {
particles.splice(i, 1);
}
}
}
canvas.addEventListener('click', function(event) {
createParticles(event.clientX, event.clientY);
hue = Math.random() * 360;
});
animate();
</script>
</body>
</html>
```
代码中通过创建Particle对象来表示每个烟花粒子,然后通过createParticles()方法在鼠标点击事件触发时生成多个粒子,通过animate()方法循环绘制和更新每个粒子的状态,实现烟花粒子特效的效果。
阅读全文