html跨年烟花代码
时间: 2024-12-31 22:31:06 浏览: 10
### HTML 实现跨年烟花效果
为了实现在网页上展示跨年烟花的效果,可以利用HTML5的`<canvas>`标签配合JavaScript来完成。下面是一个简单的例子:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>跨年烟花</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script>
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.color = `hsl(${Math.random() * 360}, 100%, 70%)`;
this.particles = [];
for (let i = 0; i < 100; ++i) { // 创建多个粒子模拟爆炸后的碎片
const angle = Math.PI * 2 / 100 * i;
this.particles.push({
vx: Math.cos(angle),
vy: Math.sin(angle),
life: Math.random() * 40 + 10,
size: Math.random() * 2 + 1
});
}
}
update(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fillStyle = 'white';
ctx.fill();
if (!this.exploded) {
this.y -= 3;
if (this.y < window.innerHeight / 2 && !this.exploded) {
setTimeout(() => {
this.explode(ctx);
}, 0);
this.exploded = true;
}
} else {
let allDead = true;
for (const particle of this.particles) {
if (particle.life > 0) {
allDead = false;
particle.vx += (Math.random() - .5) * .1;
particle.vy += (.5 + Math.random()) * .1;
particle.life--;
ctx.globalAlpha = particle.life / 50;
ctx.beginPath();
ctx.arc(
this.x + particle.vx * (50 - particle.life),
this.y + particle.vy * (50 - particle.life),
particle.size,
0,
Math.PI * 2
);
ctx.fillStyle = this.color;
ctx.fill();
}
}
if (allDead) fireworks.splice(fireworks.indexOf(this), 1); // 移除已经结束动画的对象
}
}
explode(ctx) {
new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/9642/pewsound.mp3').play(); // 添加简单音效
for (const p of this.particles) {
ctx.globalAlpha = 1;
ctx.beginPath();
ctx.arc(
this.x + p.vx * 50,
this.y + p.vy * 50,
p.size,
0,
Math.PI * 2
);
ctx.fillStyle = this.color;
ctx.fill();
}
}
}
// 初始化画布并设置尺寸适应窗口大小
function initCanvas() {
const canvas = document.getElementById('fireworksCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
return canvas.getContext('2d');
}
let fireworks = [];
function animate(ctx) {
requestAnimationFrame(() => animate(ctx));
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
if (Math.random() < 0.05 || fireworks.length === 0) {
fireworks.push(new Firework(Math.random() * window.innerWidth, window.innerHeight)); // 随机位置发射新的烟火
}
for (const f of fireworks.slice().reverse()) {
f.update(ctx);
}
}
window.onload = () => {
const context = initCanvas();
animate(context);
};
</script>
</body>
</html>
```
此代码片段展示了如何使用HTML和JavaScript创建一个基本的跨年烟花显示程序[^1]。
阅读全文