春节烟花代码html
时间: 2025-01-01 12:33:09 浏览: 6
### 创建春节烟花效果的HTML代码实现
为了创建具有春节特色的烟花效果,可以采用HTML5 Canvas配合JavaScript来绘制动画。下面是一个简单的例子:
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>春节烟花效果</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script>
(function() {
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.particles = [];
for (let i = 0; i < 100; ++i) {
this.particles.push({
angle: Math.PI * 2 / 100 * i,
speed: Math.random() * 4 + 2,
life: Math.random() * 50 + 50,
opacity: 1
});
}
}
update() {
let finished = true;
this.particles.forEach(particle => {
particle.life -= 1;
if (particle.life > 0 && particle.opacity > 0) {
finished = false;
particle.opacity -= 0.02;
this.drawParticle(particle);
}
});
return !finished;
}
drawParticle(particle) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(particle.angle);
ctx.beginPath();
ctx.arc(
particle.speed * (50 - particle.life),
0,
2,
0,
Math.PI * 2
);
ctx.fillStyle = this.color;
ctx.globalAlpha = particle.opacity;
ctx.fill();
ctx.restore();
}
}
function animateFirework(firework) {
firework.update();
requestAnimationFrame(() =>
firework.update()
? animateFirework(firework)
: null
);
}
setInterval(() => {
const firework = new Firework(Math.random() * canvas.width, canvas.height);
animateFirework(firework);
}, 1000); // 控制烟花发射频率
})();
</script>
</body>
</html>
```
这段代码定义了一个`Firework`类用来表示每一个单独的烟花爆炸过程,并通过定时器每隔一秒随机位置触发一次新的烟花爆炸[^1]。
阅读全文