使用 HTML5 Canvas 繪製煙火粒子系統:發射、爆炸、重力、風力、淡出、循環重生。比早期 DOM 版效能優越、視覺效果更豐富。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas 煙火動畫</title>
<style>
body, html { margin:0; padding:0; height:100%; overflow:hidden; background:#000; }
canvas { display:block; }
</style>
</head>
<body>
<canvas id="fw"></canvas>
<script>
const canvas = document.getElementById('fw');
const ctx = canvas.getContext('2d');
let W, H;
function resize() { W = canvas.width = innerWidth; H = canvas.height = innerHeight; }
window.addEventListener('resize', resize);
resize();
class Particle {
constructor(x, y, hue) {
this.x = x; this.y = y;
this.vx = (Math.random()-0.5)*6;
this.vy = (Math.random()-0.5)*6 - 5;
this.radius = 2 + Math.random()*3;
this.hue = hue || Math.random()*360;
this.alpha = 1;
this.decay = 0.015 + Math.random()*0.01;
}
update() {
this.vy += 0.08; // gravity
this.x += this.vx;
this.y += this.vy;
this.alpha -= this.decay;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
ctx.fillStyle = `hsla(${this.hue}, 100%, 60%, ${this.alpha})`;
ctx.fill();
}
}
const particles = [];
function spawnFirework() {
const x = Math.random() * W;
const y = H;
const hue = Math.random() * 360;
for (let i=0; i<30; i++) particles.push(new Particle(x, y, hue));
}
let lastSpawn = 0;
function loop(ts) {
ctx.fillStyle = 'rgba(0,0,0,0.2)'; // 殘影效果
ctx.fillRect(0, 0, W, H);
if (ts - lastSpawn > 800) { spawnFirework(); lastSpawn = ts; }
for (let i = particles.length-1; i>=0; i--) {
const p = particles[i];
p.update();
p.draw();
if (p.alpha <= 0) particles.splice(i, 1);
}
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
</script>
</body>
</html>
prefers-reduced-motion)