使用 HTML5 Canvas 打造高效能的飛雪粒子系統,3000 顆雪花在 60fps 下流暢運作。本文完整拆解粒子初始化、物理模擬(重力、風力、擴散)、邊界循環重生、渲染管線優化,並提供關鍵參數調教對照表,讓你輕鬆客製化浪漫冬日氛圍。
particles[],每顆雪花擁有 {x, y, r, d}(座標、半徑、密度/相位偏移),避免運行時頻繁 GC。angle += 0.01,y += Math.cos(angle + d) + 1 + r/2(下落+擺動),x += Math.sin(angle) * 2(水平飄移)。ctx.clearRect → ctx.fillStyle → ctx.beginPath → 批次 arc → ctx.fill(),單次 fill() 繪製所有雪花,極大降低 Draw Call。<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Canvas Snowfall</title>
<style>body{margin:0;background:#6b92b9;overflow:hidden}canvas{display:block;position:fixed;top:0;left:0;z-index:9999;pointer-events:none}</style></head>
<body>
<canvas id="snow"></canvas>
<script>
const canvas = document.getElementById('snow'), ctx = canvas.getContext('2d');
let W, H, particles = [], angle = 0, mp = 3000; // 粒子上限
function resize() { W = canvas.width = innerWidth; H = canvas.height = innerHeight; }
window.addEventListener('resize', resize); resize();
function initParticles() {
particles = [];
for (let i=0; i W+5 || p.x < -5 || p.y > H) {
if (i % 3 > 0) particles[i] = {x:Math.random()*W, y:-10, r:p.r, d:p.d};
else particles[i] = {x: Math.sin(angle)>0 ? -5 : W+5, y:Math.random()*H, r:p.r, d:p.d};
}
}
}
requestAnimationFrame(draw);
</script></body></html>
| 參數 | 代碼位置 | 影響效果 | 建議調整範圍 |
|---|---|---|---|
| 雪花數量 | mp = 3000 | 密度、效能 | 1000~5000(視裝置效能) |
| 半徑範圍 | r: Math.random()*3+1 | 大小變化、遠近感 | 1~5px |
| 下落基礎速度 | + 1 + p.r/2 | 整體下落快慢 | 0.5~3 |
| 水平飄移幅度 | Math.sin(angle) * 2 | 風力強度 | 0.5~5 |
| 擺動頻率 | angle += 0.01 | 擺動速度 | 0.005~0.03 |
| 幀率 | requestAnimationFrame | 流暢度/耗電 | 固定 60fps,若效能不足可改 setInterval(draw, 16) |
beginPath + 多次 arc + 單次 fill,避免 3000 次 Draw Call。particles[i] = {...},不 push/splice。pointer-events:none:Canvas 置頂不阻擋下層互動。navigator.hardwareConcurrency 或 FPS 低於 30 時動態降低 mp。只需修改 ctx.fillStyle(漸層/圖片 createPattern)、r 範圍、update() 物理公式(加入旋轉、縮放、透明度變化),即可衍生出四季主題特效。
