萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作綻放煙火動畫(Canvas 版)

使用 HTML5 Canvas 繪製煙火粒子系統:發射、爆炸、重力、風力、淡出、循環重生。比早期 DOM 版效能優越、視覺效果更豐富。

核心架構

  • Fire 粒子類別:位置、速度、半徑、顏色、生命週期
  • Fireworks 控制器:管理粒子陣列、重力、風力、地板反彈、定時重置
  • requestAnimationFrame 驅動 60fps 動畫迴圈

完整可執行範例

<!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>

進階擴充方向

  • 多種煙火類型:意志、分裂、尾跡、音樂同步
  • WebGL / Three.js / Canvas 2D 濾鏡 提升粒子量級
  • 加入聲音合成(Web Audio API)模擬爆炸聲
  • 提供「減少動畫」偏好開關(prefers-reduced-motion)
copyright © 萬盛學電腦網 all rights reserved