js实现烟花
使用Canvas绘制烟花效果
在HTML中创建一个Canvas元素,并设置合适的宽度和高度
<canvas id="fireworksCanvas"></canvas>
<style>
canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
}
</style>
初始化Canvas上下文并设置基础参数
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particles = [];
const fireworks = [];
let hue = 120;
创建烟花粒子类

class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.velocity = {
x: (Math.random() - 0.5) * 8,
y: (Math.random() - 0.5) * 8
};
this.alpha = 1;
this.friction = 0.95;
this.gravity = 0.2;
this.size = Math.random() * 3 + 1;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.restore();
}
update() {
this.velocity.x *= this.friction;
this.velocity.y *= this.friction;
this.velocity.y += this.gravity;
this.x += this.velocity.x;
this.y += this.velocity.y;
this.alpha -= 0.01;
}
}
创建烟花类并实现爆炸效果
class Firework {
constructor() {
this.x = Math.random() * canvas.width;
this.y = canvas.height;
this.targetY = Math.random() * canvas.height / 2;
this.speed = 3;
this.angle = Math.atan2(this.targetY - this.y, this.x - this.x);
this.velocity = {
x: 0,
y: -this.speed
};
this.color = `hsl(${hue}, 100%, 50%)`;
this.trail = [];
this.trailLength = 5;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, 3, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
update() {
this.y += this.velocity.y;
if (this.y <= this.targetY) {
this.explode();
fireworks.splice(fireworks.indexOf(this), 1);
}
}
explode() {
for (let i = 0; i < 100; i++) {
particles.push(new Particle(this.x, this.y, this.color));
}
}
}
动画循环和烟花发射控制

function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
hue += 0.5;
if (Math.random() < 0.03) {
fireworks.push(new Firework());
}
fireworks.forEach(firework => {
firework.draw();
firework.update();
});
particles.forEach((particle, index) => {
if (particle.alpha > 0) {
particle.draw();
particle.update();
} else {
particles.splice(index, 1);
}
});
requestAnimationFrame(animate);
}
animate();
添加交互功能
点击屏幕发射烟花
canvas.addEventListener('click', (e) => {
const firework = new Firework();
firework.x = e.clientX;
firework.y = e.clientY;
firework.targetY = e.clientY - 100;
firework.velocity.y = -5;
fireworks.push(firework);
});
性能优化
限制粒子数量防止卡顿
function animate() {
// ...其他代码...
if (particles.length > 2000) {
particles.splice(0, 500);
}
// ...其他代码...
}
调整重力效果和粒子数量
// 在Particle类中修改
this.gravity = Math.random() * 0.3;
// 在explode方法中修改粒子数量
for (let i = 0; i < Math.random() * 50 + 50; i++) {
particles.push(new Particle(this.x, this.y, this.color));
}






