答案:使用HTML5 Canvas和JavaScript创建烟花特效,通过定义粒子类模拟爆炸效果,结合火箭上升与粒子扩散,利用requestAnimationFrame实现流畅动画。

用HTML5制作烟花特效,核心是利用Canvas绘制动态粒子系统。通过JavaScript控制粒子的运动、颜色、透明度和生命周期,模拟出烟花爆炸的视觉效果。下面是一个简洁实用的实现方法。
1. 创建Canvas画布
在HTML中添加元素,作为绘图区域。设置宽高并获取2D渲染上下文。
JavaScript中获取画布:
const canvas = document.getElementById('fireworkCanvas');
const ctx = canvas.getContext('2d');
2. 定义粒子对象
每个烟花粒子包含位置、速度、颜色、透明度和存活时间等属性。使用构造函数或类定义粒子行为。
立即学习“前端免费学习笔记(深入)”;
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.alpha = 1;
this.life = 60; // 存活帧数
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.alpha -= 1 / this.life;
this.size -= 0.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.fill();
ctx.restore();
}
}
3. 实现烟花发射与爆炸
模拟烟花先上升再爆炸的过程。创建“火箭”粒子向上飞行,到达指定高度后生成多个爆炸粒子。
let particles = []; let rockets = [];function launchRocket() { const x = Math.random() canvas.width; const rocket = { x, y: canvas.height, speedY: -Math.random() 5 - 3, color:
hsl(${Math.random() * 360}, 100%, 50%), explode: false }; rockets.push(rocket); }function explode(x, y, color) { for (let i = 0; i < 50; i++) { particles.push(new Particle(x, y)); } }
4. 动画循环与渲染
使用requestAnimationFrame持续更新画面。清理画布,更新所有粒子和火箭状态,触发爆炸。
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 更新火箭
rockets.forEach((rocket, index) => {
rocket.y += rocket.speedY;
if (rocket.y < 200 + Math.random() * 100 && !rocket.explode) {
rocket.explode = true;
explode(rocket.x, rocket.y, rocket.color);
rockets.splice(index, 1);
} else {
ctx.fillStyle = rocket.color;
ctx.fillRect(rocket.x, rocket.y, 2, 5);
}
});
// 更新粒子
particles.forEach((p, i) => {
p.update();
p.draw();
if (p.alpha <= 0 || p.size <= 0.2) {
particles.splice(i, 1);
}
});
if (Math.random() < 0.03) launchRocket();
requestAnimationFrame(animate);
}
launchRocket();
animate();
基本上就这些。通过调整粒子数量、速度、颜色渐变和衰减方式,可以让效果更逼真。加入鼠标点击触发烟花、声音或背景星空,能进一步提升体验。关键是控制好生命周期和透明度变化,让视觉自然流畅。











