js实现烟花
实现基础烟花效果
创建画布并初始化基础参数:
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particles = [];
定义粒子类:
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.decay = Math.random() * 0.015 + 0.01;
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.y += 0.05;
this.x += this.velocity.x;
this.y += this.velocity.y;
this.alpha -= this.decay;
this.draw();
return this.alpha > 0;
}
}
创建爆炸效果函数
实现烟花爆炸效果:
function createFirework(x, y) {
const particleCount = 150;
const hue = Math.floor(Math.random() * 360);
for (let i = 0; i < particleCount; i++) {
const color = `hsl(${hue}, 100%, 50%)`;
particles.push(new Particle(x, y, color));
}
}
动画循环与交互处理
设置动画循环:
function animate() {
requestAnimationFrame(animate);
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
particles = particles.filter(particle => particle.update());
}
animate();
添加点击事件监听:
canvas.addEventListener('click', (e) => {
createFirework(e.clientX, e.clientY);
});
自动发射烟花功能
实现自动发射效果:
function autoFire() {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height * 0.5;
createFirework(x, y);
setTimeout(autoFire, Math.random() * 1000 + 500);
}
autoFire();
完整HTML结构示例
基础HTML结构:
<!DOCTYPE html>
<html>
<head>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script src="fireworks.js"></script>
</body>
</html>
进阶效果优化
添加拖尾效果:
class Particle {
// 在构造函数中添加
this.history = [];
this.maxHistory = 5;
update() {
// 记录位置历史
this.history.push({x: this.x, y: this.y});
if (this.history.length > this.maxHistory) {
this.history.shift();
}
// 绘制拖尾
ctx.save();
ctx.globalAlpha = this.alpha * 0.5;
for (let i = 0; i < this.history.length; i++) {
const pos = this.history[i];
const size = this.size * (i / this.history.length);
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(pos.x, pos.y, size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
ctx.restore();
// 原有更新逻辑...
}
}
实现多色烟花:
function createMultiColorFirework(x, y) {
const particleCount = 200;
const colorCount = 5;
for (let i = 0; i < particleCount; i++) {
const hue = Math.floor(Math.random() * 360);
const color = `hsl(${hue}, 100%, 50%)`;
particles.push(new Particle(x, y, color));
}
}






