新年烟花html网页代码
时间: 2024-12-30 22:33:12 浏览: 25
### 实现新年烟花效果的HTML网页代码
为了创建具有新年烟花效果的HTML页面,可以利用HTML5 Canvas API 和 JavaScript 来绘制动画。下面是一个简单的例子来展示如何实现这一特效。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>New Year Fireworks</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script>
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.velocity = { x: (Math.random() - 0.5) * 10, y: (Math.random() - 0.7) * 10 };
this.lifetime = Math.random() * 100 + 50;
}
update() {
this.x += this.velocity.x;
this.y += this.velocity.y;
this.lifetime -= 2;
if (this.lifetime <= 0 || this.y >= window.innerHeight) {
particles.splice(particles.indexOf(this), 1);
}
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
let canvas = document.getElementById('fireworksCanvas');
let context = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
let particles = [];
function createFirework(event) {
let numParticles = 100;
let fireworkColor = `hsl(${Math.random() * 360}, 100%, 50%)`;
for (let i = 0; i < numParticles; ++i) {
particles.push(new Particle(
event.clientX,
event.clientY,
fireworkColor));
}
}
document.body.addEventListener('click', createFirework);
function animate() {
requestAnimationFrame(animate);
context.clearRect(0, 0, innerWidth, innerHeight);
particles.forEach((particle) => particle.update());
particles.forEach((particle) => particle.draw(context));
}
animate();
</script>
</body>
</html>
```
这段代码定义了一个`Particle`类用于表示单个粒子,并通过监听鼠标点击事件触发烟花爆炸的效果。每次点击都会生成一组带有随机颜色的新粒子,在画布上模拟出烟花绽放的过程[^1]。
阅读全文