實現綻放煙火動畫:點擊/自動產生煙火 → 火箭上升 → 爆炸散開 → 粒子重力下落淡出。採用面向對象架構,分離粒子邏輯、煙火生命週期、渲染引擎。
// 命名空間
const Fireworks = {};
// 工具函數
Fireworks.util = {
random(min, max) { return Math.random() * (max - min) + min; },
randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; },
randomColor() {
const hues = [0, 30, 60, 120, 180, 240, 270, 300]; // 紅橙黃綠青藍紫粉
return `hsl(${hues[Math.floor(Math.random() * hues.length)]}, 100%, 60%)`;
},
distance(x1, y1, x2, y2) {
const dx = x2 - x1, dy = y2 - y1;
return Math.sqrt(dx*dx + dy*dy);
}
};
Fireworks.Particle = class Particle {
constructor(x, y, color, angle, speed, gravity, friction, decay) {
this.x = x; this.y = y;
this.color = color;
this.angle = angle; // 移動角度 (弧度)
this.speed = speed; // 初速度
this.gravity = gravity; // 重力加速度
this.friction = friction; // 空氣阻力
this.decay = decay; // 透明度衰減率
this.alpha = 1; // 當前透明度
this.trail = []; // 軌跡點陣列 (長曝光效果)
this.maxTrail = 20;
}
update() {
// 記錄軌跡
this.trail.push({ x: this.x, y: this.y, alpha: this.alpha });
if (this.trail.length > this.maxTrail) this.trail.shift();
// 物理更新
this.speed *= this.friction;
this.x += Math.cos(this.angle) * this.speed;
this.y += Math.sin(this.angle) * this.speed + this.gravity;
this.alpha -= this.decay;
}
draw(ctx) {
// 繪製軌跡 (漸變淡出)
if (this.trail.length > 1) {
ctx.beginPath();
ctx.moveTo(this.trail[0].x, this.trail[0].y);
for (let i = 1; i < this.trail.length; i++) {
const p = this.trail[i];
ctx.lineTo(p.x, p.y);
}
ctx.strokeStyle = this.color.replace("60%", `${this.alpha * 60}%`);
ctx.lineWidth = 2;
ctx.stroke();
}
// 繪製粒子本體
ctx.beginPath();
ctx.arc(this.x, this.y, Math.max(1, this.alpha * 3), 0, Math.PI * 2);
ctx.fillStyle = this.color.replace("60%", `${this.alpha * 60}%`);
ctx.fill();
}
isDead() { return this.alpha <= 0; }
};
Fireworks.Firework = class Firework {
constructor(canvas, options = {}) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.x = options.x || Fireworks.util.randomInt(100, canvas.width - 100);
this.y = canvas.height; // 從底部發射
this.targetY = options.y || Fireworks.util.randomInt(100, canvas.height * 0.4);
this.color = options.color || Fireworks.util.randomColor();
this.speed = options.speed || Fireworks.util.random(4, 8);
this.angle = -Math.PI / 2; // 直上
this.gravity = 0.05;
this.friction = 0.99;
this.exploded = false;
this.particles = [];
this.hue = parseInt(this.color.match(/\d+/)[0]); // 提取色相
}
update() {
if (!this.exploded) {
// 上升階段
this.y += Math.sin(this.angle) * this.speed;
this.speed *= this.friction;
this.y += this.gravity; // 重力漸減速
// 留下上升軌跡
this.particles.push(new Fireworks.Particle(
this.x, this.y, this.color, 0, 0, 0, 1, 0.02
));
this.particles[this.particles.length - 1].trail = []; // 上升軌跡不畫尾巴
// 到達目標高度 → 爆炸
if (this.y <= this.targetY) this.explode();
} else {
// 爆炸後:更新所有粒子
this.particles = this.particles.filter(p => {
p.update();
return !p.isDead();
});
}
}
explode() {
this.exploded = true;
const particleCount = Fireworks.util.randomInt(60, 100);
const explosionPower = Fireworks.util.random(3, 6);
for (let i = 0; i < particleCount; i++) {
const angle = Fireworks.util.random(0, Math.PI * 2);
const speed = Fireworks.util.random(1, explosionPower);
// 粒子顏色:主色相 ±30度 變化
const color = `hsl(${this.hue + Fireworks.util.random(-30, 30)}, 100%, 60%)`;
this.particles.push(new Fireworks.Particle(
this.x, this.y, color, angle, speed, 0.08, 0.97, 0.015
));
}
// 爆炸閃光
this.particles.push(new Fireworks.Particle(
this.x, this.y, `hsl(${this.hue}, 100%, 80%)`, 0, 0, 0, 1, 0.1
));
this.particles[this.particles.length - 1].maxTrail = 0;
}
draw() {
if (!this.exploded) {
// 繪製火箭本體
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
this.ctx.fillStyle = this.color;
this.ctx.fill();
}
// 繪製所有粒子
this.particles.forEach(p => p.draw(this.ctx));
}
isDead() { return this.exploded && this.particles.length === 0; }
};
Fireworks.Controller = class Controller {
constructor(canvasId) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext("2d");
this.fireworks = [];
this.autoTimer = null;
this.resize();
this.bindEvents();
this.animate();
}
resize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
bindEvents() {
window.addEventListener("resize", () => this.resize());
// 點擊發射
this.canvas.addEventListener("click", (e) => {
this.launch({ x: e.clientX, y: e.clientY });
});
// 鍵盤空白鍵發射
document.addEventListener("keydown", (e) => {
if (e.code === "Space") {
e.preventDefault();
this.launch({ x: Fireworks.util.randomInt(100, this.canvas.width - 100) });
}
});
}
launch(options = {}) {
this.fireworks.push(new Fireworks.Firework(this.canvas, options));
}
startAuto(interval = 1500) {
this.stopAuto();
this.autoTimer = setInterval(() => {
this.launch({
x: Fireworks.util.randomInt(100, this.canvas.width - 100),
y: Fireworks.util.randomInt(100, this.canvas.height * 0.4)
});
}, interval);
}
stopAuto() { clearInterval(this.autoTimer); }
animate() {
// 清除畫布 (半透明黑色產生拖尾效果)
this.ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// 更新與繪製
this.fireworks = this.fireworks.filter(fw => {
fw.update();
fw.draw();
return !fw.isDead();
});
requestAnimationFrame(() => this.animate());
}
};
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>JS 煙火特效</title>
<style>
body { margin: 0; overflow: hidden; background: #000; height: 100vh; }
canvas { display: block; }
#controls {
position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
display: flex; gap: 10px; z-index: 100;
}
button { padding: 10px 20px; font-size: 14px; border: none; border-radius: 20px;
background: rgba(255,255,255,0.2); color: #fff; cursor: pointer; backdrop-filter: blur(10px);
}
button:hover { background: rgba(255,255,255,0.4); }
</style>
</head><body>
<canvas id="fw-canvas"></canvas>
<div id="controls">
<button id="btn-auto">自動燃放</button>
<button id="btn-stop">停止自動</button>
<button id="btn-clear">清空畫面</button>
</div>
<script src="fireworks.js"></script>
<script>
const controller = new Fireworks.Controller("fw-canvas");
document.getElementById("btn-auto").onclick = () => controller.startAuto();
document.getElementById("btn-stop").onclick = () => controller.stopAuto();
document.getElementById("btn-clear").onclick = () => controller.fireworks = [];
</script>
</body></html>
| 策略 | 實作 | 效果 |
|---|---|---|
| Object Pooling | 預建粒子池,重用而非 new/delete | 減少 GC、穩定 60fps |
| 離屏剔除 | 粒子超出畫布範圍直接標記死亡 | 減少無效繪製 |
| 批次繪製 | 相同顏色粒子合併路徑繪製 | 減少 drawCall |
| Web Workers | 物理計算移至 Worker,主執行緒只渲染 | 多核心加速、不阻塞 UI |
| WebGL/GPU | Shader 並行計算百萬粒子 | 質的飛躍、需三維數學基礎 |
此煙火特效展示了面向對象粒子系統的經典架構:Particle (微觀行為) + Firework (巨觀生命週期) + Controller (調度與互動)。核心物理模型極簡 (位置、速度、加速度、阻力、衰減),却能產生豐富視覺變化。現代專案建議直接使用 @react-three/fiber + drei 的 <Fireworks> 或 PixiJS 粒子系統,專注於創意設計而非底層實作。