萬盛學電腦網

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

Canvas 粒子碰撞動畫:隨機彩色球體彈射特效完整實作

效果特色

  • 多顆隨機半徑、顏色、速度的球體在 Canvas 內彈射
  • 邊界檢測自動反彈,支援暫停/繼續/新增球體
  • 使用 `requestAnimationFrame` 替代 `setTimeout`,效能更穩定
  • 模組化寫法,易於擴展物理引擎(重力、摩擦力、碰撞合併)

核心架構:`ParticleSystem` 類別

class ParticleSystem {
  constructor(canvasId, options = {}) {
    this.canvas = document.getElementById(canvasId);
    this.ctx = this.canvas.getContext('2d');
    this.particles = [];
    this.running = false;
    this.rafId = null;

    // 可配置參數
    this.radiusRange = options.radiusRange || [5, 20];
    this.speedRange  = options.speedRange  || [-5, 5];
    this.maxParticles = options.maxParticles || 200;

    this._resize();
    window.addEventListener('resize', () => this._resize());
  }

  _resize() {
    const dpr = window.devicePixelRatio || 1;
    this.canvas.width  = this.canvas.clientWidth * dpr;
    this.canvas.height = this.canvas.clientHeight * dpr;
    this.ctx.scale(dpr, dpr);
    this.width  = this.canvas.clientWidth;
    this.height = this.canvas.clientHeight;
  }

  add(count = 1) {
    for (let i = 0; i < count && this.particles.length < this.maxParticles; i++) {
      const r = this._rand(...this.radiusRange);
      const x = this._rand(r, this.width - r);
      const y = this._rand(r, this.height - r);
      const color = `rgba(${this._rand(0,255)},${this._rand(0,255)},${this._rand(0,255)},0.6)`;
      let vx = this._rand(...this.speedRange);
      let vy = this._rand(...this.speedRange);
      if (vx === 0) vx = 1;
      if (vy === 0) vy = 1;
      this.particles.push({ x, y, r, color, vx, vy });
    }
  }

  _rand(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  _update() {
    this.particles.forEach(p => {
      // 邊界反彈
      if (p.x + p.r >= this.width)  { p.vx = -Math.abs(p.vx); }
      if (p.x - p.r <= 0)           { p.vx =  Math.abs(p.vx); }
      if (p.y + p.r >= this.height) { p.vy = -Math.abs(p.vy); }
      if (p.y - p.r <= 0)           { p.vy =  Math.abs(p.vy); }

      p.x += p.vx;
      p.y += p.vy;
    });
  }

  _draw() {
    this.ctx.clearRect(0, 0, this.width, this.height);
    this.particles.forEach(p => {
      this.ctx.beginPath();
      this.ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
      this.ctx.fillStyle = p.color;
      this.ctx.fill();
    });
  }

  _loop() {
    this._update();
    this._draw();
    if (this.running) this.rafId = requestAnimationFrame(() => this._loop());
  }

  start() {
    if (!this.running) {
      this.running = true;
      this._loop();
    }
  }

  stop() {
    this.running = false;
    cancelAnimationFrame(this.rafId);
  }
}

HTML 與控制按鈕

<canvas id="canvas" style="display:block;margin:auto;border:1px solid #ddd;background:#111"></canvas>
<div style="text-align:center;margin-top:12px">
  <button id="btnStart">開始</button>
  <button id="btnStop">暫停</button>
  <button id="btnAdd">新增 10 顆</button>
</div>

<script>
const system = new ParticleSystem('canvas', { radiusRange: [8, 25], speedRange: [-6, 6] });
system.add(20);
system.start();

document.getElementById('btnStart').onclick = () => system.start();
document.getElementById('btnStop').onclick  = () => system.stop();
document.getElementById('btnAdd').onclick   = () => system.add(10);
</script>

效能優化關鍵點

優化項目說明
`requestAnimationFrame`瀏覽器自動對齊螢幕重繪率(60/120Hz),避免 `setTimeout` 抖動
`devicePixelRatio` 適配高 DPI 螢幕(Retina、4K)不模糊,`ctx.scale(dpr, dpr)`
離屏 Canvas / OffscreenCanvas大量粒子時可移至 Web Worker,釋放主執行緒
物件池重複使用粒子物件,減少 GC 壓力
空間分割Quadtree / Grid 只檢測鄰近粒子碰撞,O(n²) → O(n log n)

擴展想法

  • 滑鼠互動:`mousemove` 記錄座標,粒子受吸引/排斥力影響。
  • 碰撞合併:兩球相撞合併質量、動量守恆,模擬流體。
  • 圖片紋理:`ctx.drawImage` 替代 `arc`,做雪花、氣泡、表情符號雨。
  • WebGL 升級:超過 1 萬粒子建議改用 Three.js / PixiJS / 原生 WebGL。

結語

Canvas 粒子系統是前端圖形入門的最佳練習:涵蓋動畫循環、向量物理、邊界檢測、高 DPI 適配、效能分析。掌握此範例,即可輕鬆擴展粒子特效、遊戲原型、資料視覺化背景等進階應用。

copyright © 萬盛學電腦網 all rights reserved