h5烟花实现
H5烟花实现方法
使用HTML5的Canvas结合JavaScript可以轻松实现烟花效果。以下是具体实现步骤:
创建Canvas画布
在HTML中创建一个Canvas元素作为烟花展示区域:
<canvas id="fireworksCanvas"></canvas>
基础样式设置
为Canvas添加基础CSS样式确保全屏显示:
#fireworksCanvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
JavaScript核心逻辑
实现烟花粒子系统需要以下关键组件:

初始化画布
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
烟花粒子类
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;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 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;
}
}
烟花发射函数

function createFirework(x, y) {
const color = `hsl(${Math.random() * 360}, 100%, 50%)`;
const particleCount = 150;
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle(x, y, color));
}
}
动画循环
let particles = [];
function animate() {
requestAnimationFrame(animate);
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
particles.forEach((particle, index) => {
particle.update();
particle.draw();
if (particle.alpha <= 0) {
particles.splice(index, 1);
}
});
}
animate();
触发烟花效果
通过点击事件或自动触发烟花:
// 点击触发
canvas.addEventListener('click', (e) => {
createFirework(e.clientX, e.clientY);
});
// 自动发射
setInterval(() => {
createFirework(
Math.random() * canvas.width,
Math.random() * canvas.height * 0.5
);
}, 1000);
性能优化建议
- 使用对象池复用粒子对象
- 限制同时存在的粒子数量
- 对于移动端减少粒子数量
- 添加resize事件处理:
window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; });
扩展效果
可通过以下方式增强视觉效果:
- 添加拖尾效果
- 实现不同形状的烟花爆裂
- 加入声音效果
- 使用WebGL实现3D烟花
完整实现示例可在CodePen等平台找到现成案例参考。




