Canvas 動畫/遊戲幀率不穩?90% 是繪製策略問題。總結 10 大優化鐵律,從緩存預繪到分層渲染,徹底榨乾 GPU 性能。
// ❌ 每幀重繪文字
ctx.font = '24px Arial';
ctx.fillStyle = 'blue';
ctx.fillText('Press Esc to exit', 5, 50);
// ✅ 離屏 Canvas 預繪,主循環直接 drawImage
const offscreen = document.createElement('canvas');
offscreen.width = 450; offscreen.height = 54;
const octx = offscreen.getContext('2d');
octx.font = '24px Arial';
octx.fillStyle = 'blue';
octx.fillText('Press Esc to exit', 5, 50);
// 主循環
function render(ctx) {
ctx.drawImage(offscreen, 0, 0);
requestAnimationFrame(() => render(ctx));
}
原則:緩存 Canvas 尺寸 ≤ 實際 Canvas,避免不必要像素處理。
// ❌ 每段線獨立 beginPath+stroke(極慢)
points.forEach((p,i) => {
if(i===0) return;
ctx.beginPath();
ctx.moveTo(points[i-1].x, points[i-1].y);
ctx.lineTo(p.x, p.y);
ctx.stroke();
});
// ✅ 一次 beginPath,累積路徑,一次 stroke
ctx.beginPath();
points.forEach((p,i) => {
if(i===0) ctx.moveTo(p.x, p.y);
else ctx.lineTo(p.x, p.y);
});
ctx.stroke();
// ❌ 迴圈中頻繁切換 fillStyle
for(i=0;i<10;i++) {
ctx.fillStyle = i%2?'blue':'red';
ctx.fillRect(0, i*10, 400, 10);
}
// ✅ 分組繪製
ctx.fillStyle = 'red';
for(i=0;i<5;i++) ctx.fillRect(0, (i*2)*10, 400, 10);
ctx.fillStyle = 'blue';
for(i=0;i<5;i++) ctx.fillRect(0, (i*2+1)*10, 400, 10);
避免 clearRect(0,0,w,h) 全屏清屏,改用髒矩形算法追蹤變化區域。
<canvas id="bg" style="position:absolute;z-index:0" width="640" height="480"></canvas>
<canvas id="fg" style="position:absolute;z-index:1" width="640" height="480"></canvas>
背景靜態層、前景動態層、UI 層分離,互不干擾。
shadowBlur、filter: blur() 極耗 GPU,非核心視覺勿用;若必須用,限制範圍、降低頻率。
所有座標、尺寸取整(Math.round 或 \|0),消除模糊與額外插值運算。
巢狀變換/樣式變更時,save() 保存現狀,restore() 彈出,避免手動逆向重置錯誤。
連續 translate/rotate/scale 會累積矩陣乘法,若順序固定可預計算合併矩陣用 setTransform 一次應用。
ctx.clearRect(0,0,w,h):標準、保留狀態堆疊canvas.width = canvas.width:暴力重置(清空狀態堆疊、綁定事件可能失效),僅適用簡單場景requestAnimationFrame 回調參數 timestamp 計算幀耗時canvas.getContext('2d', {desynchronized: true}) 降低延遲 (Chrome)優化是測量驅動的:先 Profile,找熱點,對症下藥,再驗證。