Canvas 看似簡單,實則暗藏效能陷阱與渲染差異。總結 20 條實戰精華,助你寫出高效、穩健的繪圖代碼。
<canvas width="800" height="600"> 設定繪圖緩衝區解析度;CSS 只控制顯示大小,避免模糊或異常拉伸。const canvas = document.getElementById('c');
if (canvas.getContext) { const ctx = canvas.getContext('2d'); /* ... */ }
fillRect、strokeRect、clearRect、rect(路徑)。beginPath() 開啟新層,避免上一筆路徑污染。fill() 會自動閉合路徑,無需 closePath()。quadraticCurveTo 在 Firefox 有 Bug,改用三次 bezierCurveTo 替代。fillStyle/strokeStyle。
// 差:每次迴圈切換顏色
for (i) { ctx.fillStyle = i%2?'red':'blue'; ctx.fillRect(...); }
// 優:分組繪製
ctx.fillStyle='red'; for(i even) ctx.fillRect(...);
ctx.fillStyle='blue'; for(i odd) ctx.fillRect(...);
lineWidth 用整數+0.5 修正 1px 模糊;lineCap (butt/round/square) 控制端點;lineJoin (miter/round/bevel) 控制轉角。save()/restore() 管理變換與樣式巢狀結構。transform(a,b,c,d,e,f) 對應縮放、旋轉、傾斜、平移;setTransform 重置後應用。drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) 九參數版支援裁切縮放。globalAlpha 或 RGBA 色值單獨控制。clearRect(0,0,w,h) 標準做法;canvas.width = canvas.width 重置畫布(副作用:清空狀態堆疊),謹慎使用。clearRect → 狀態更新 → 重繪 循環,配合 requestAnimationFrame。drawImage(offscreenCanvas)。shadowBlur)、模糊極耗效能,非必要勿用。Canvas 教程 (MDN) —— 最權威、持續更新的中文參考。