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