用js写一段烟花动画代码
时间: 2023-05-22 12:02:25 浏览: 111
JavaScript实现的简单烟花特效代码
这是一段简单的烟花动画代码,你可以在浏览器中使用 HTML5 canvas 来运行它:
```
<html>
<head>
<style>
canvas {
display: block;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="fireworks"></canvas>
<script>
var canvas = document.getElementById("fireworks");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var particles = [];
var color = "red";
function Particle(x, y) {
this.x = x;
this.y = y;
this.speed = Math.random() * 5 + 2;
this.direction = Math.random() * Math.PI * 2;
this.life = Math.random() * 100 + 50;
this.remaining_life = this.life;
this.radius = Math.random() * 3 + 1;
}
Particle.prototype.update = function() {
this.remaining_life--;
this.x += Math.cos(this.direction) * this.speed;
this.y += Math.sin(this.direction) * this.speed;
this.radius -= 0.01;
};
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
var gradient = ctx.createRadialGradient(
this.x,
this.y,
0,
this.x,
this.y,
this.radius
);
gradient.addColorStop(0, color);
gradient.addColorStop(0.5, "white");
gradient.addColorStop(1, color);
ctx.fillStyle = gradient;
ctx.fill();
ctx.closePath();
};
canvas.addEventListener("click", function(event) {
var x = event.clientX;
var y = event.clientY;
for (var i = 0; i < 100; i++) {
particles.push(new Particle(x, y));
}
});
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
var particle = particles[i];
particle.update();
particle.draw();
if (particle.remaining_life < 0 || particle.radius < 0) {
particles.splice(i, 1);
i--;
}
}
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>
```
这
阅读全文