早期想在網頁上畫圖,只能靠一張張圖片拼湊,或用 Flash、VML 這類外掛與私有技術。Canvas 的出現改變了這件事:瀏覽器直接提供一塊可繪製的畫布,任何線條、色塊、文字、甚至逐像素的影像處理,都能用 JavaScript 即時完成。本文說明 Canvas 的核心用法,並示範如何把它包成一套好重複使用的 2D 繪圖函式集。
Canvas 只是一塊空白區域,真正的繪圖能力來自 context 物件:
<canvas id="stage" width="600" height="400"></canvas>
const canvas = document.getElementById('stage');
const ctx = canvas.getContext('2d');
所有後續的線條、填色、文字都透過 ctx 下達。若需要像素級操作,同一塊畫布也能改用 getContext('webgl') 或 '2d' 搭配 getImageData 處理。
原始 API 冗長且容易寫錯狀態,實務上會包一層薄薄的工具函式,讓呼叫端只關心「畫什麼」:
const Draw = {
rect(x, y, w, h, fill, stroke) {
if (fill) { ctx.fillStyle = fill; ctx.fillRect(x, y, w, h); }
if (stroke) { ctx.strokeStyle = stroke; ctx.strokeRect(x, y, w, h); }
},
circle(cx, cy, r, fill, stroke) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
fill && (ctx.fillStyle = fill, ctx.fill());
stroke && (ctx.strokeStyle = stroke, ctx.stroke());
},
line(x1, y1, x2, y2, color, width = 1) {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
},
text(str, x, y, font = '16px sans-serif', color = '#000') {
ctx.font = font;
ctx.fillStyle = color;
ctx.fillText(str, x, y);
},
clear() { ctx.clearRect(0, 0, canvas.width, canvas.height); }
};
Draw.rect(20, 20, 120, 80, '#4a90d9');
Draw.circle(300, 200, 60, null, '#e8503a');
Draw.line(0, 380, 600, 380, '#333', 2);
Draw.text('Hello Canvas', 20, 340, 'bold 20px sans-serif', '#222');
直接畫在 canvas 上,在 Retina 等高 DPI 螢幕會顯得模糊,因為一個 CSS 像素被填成一個實際像素。做法是放大實際解析度,再用 CSS 縮回原本尺寸,並同步縮放座標系統:
const dpr = window.devicePixelRatio || 1; const cssW = 600, cssH = 400; canvas.width = cssW * dpr; canvas.height = cssH * dpr; canvas.style.width = cssW + 'px'; canvas.style.height = cssH + 'px'; ctx.scale(dpr, dpr); // 之後一律用 CSS 像素座標思考
Canvas 本身沒有動畫概念,每次更新都要重畫。用 requestAnimationFrame 讓瀏覽器在下一個刷新週期呼叫你的繪製函式,比 setInterval 更順 also 更省電:
let angle = 0;
function loop() {
Draw.clear();
Draw.rect(0, 0, 600, 400, '#fafafa');
ctx.save();
ctx.translate(300, 200);
ctx.rotate(angle);
Draw.rect(-50, -20, 100, 40, '#4a90d9');
ctx.restore();
angle += 0.02;
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
Canvas 是「像素導向」,適合大量圖形、遊戲、影像處理、資料視覺化的密集繪製,但畫好的內容不會留在 DOM 裡,無障礙與事件命中需要自己處理。SVG 是「物件導向」,每個圖形都是 DOM 節點,能直接用 CSS 設定樣式、能被搜尋引擎與螢幕閱讀器理解,適合圖示、圖表與需要互動的向量圖。選錯工具比寫錯程式更耗時間。
Canvas 的學習曲線在於它「什麼都不幫你做」——沒有版面、沒有事件、沒有無障礙樹。但也正因如此,只要願意多包一層自己的函式集,就能得到極高的自由度與效能。先熟練路徑、狀態與座標變換這三件事,其餘都是排列組合。