<canvas> 是 HTML5 核心繪圖容器,本身不具繪圖能力,需透過 JavaScript 取得 CanvasRenderingContext2D(2D)或 WebGLRenderingContext(3D)上下文才能繪圖。本文從最基礎的標籤屬性、取得上下文、尺寸與 CSS 像素的關係、備用內容處理,建立完整的 Canvas 入門知識庫。
| 屬性 | 說明 | 預設值 | 建議 |
|---|---|---|---|
width | 畫布實際像素寬度(繪圖緩衝區寬度) | 300 | 必須以屬性或 JS 明確設定,勿只靠 CSS |
height | 畫布實際像素高度 | 150 | 同上 |
id | 供 JS 選取 | — | 建議加上 |
<canvas width="640" height="480" id="c" style="width:320px;height:240px"></canvas>
```
- 繪圖緩衝區:640×480 物理像素(高解析度)
- CSS 顯示尺寸:320×240 CSS 像素(螢幕佔用面積)
- 結果:內容被縮放 2 倍顯示,適合 Retina/高 DPI 螢幕銳利度
若只設 CSS 不設 width/height → 緩衝區預設 300×150 → 被拉大顯示 → **模糊失真**。
const canvas = document.getElementById('c');
// 必須檢查支援性
if (canvas.getContext) {
const ctx = canvas.getContext('2d'); // 核心繪圖 API 入口
// ctx 現在擁有 fillRect, strokeRect, arc, drawImage, fillText... 等方法
} else {
console.warn('瀏覽器不支援 Canvas');
// 顯示備用內容或降級方案
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas Starter</title>
<style>
canvas { border:1px solid #333; background:#fafafa; display:block; margin:20px auto; }
</style>
</head>
<body>
<canvas id="c" width="600" height="400">
提示:你的瀏覽器不支援 <canvas> 標籤,請升級瀏覽器。
</canvas>
<script>
window.onload = () => {
const canvas = document.getElementById('c');
if (!canvas.getContext) return;
const ctx = canvas.getContext('2d');
// 測試繪製:紅色矩形 + 藍色圓形 + 文字
ctx.fillStyle = '#e74c3c';
ctx.fillRect(50, 50, 200, 100);
ctx.beginPath();
ctx.arc(400, 100, 50, 0, Math.PI*2);
ctx.fillStyle = '#3498db';
ctx.fill();
ctx.font = '24px Microsoft JhengHei, sans-serif';
ctx.fillStyle = '#2c3e50';
ctx.fillText('Hello Canvas!', 50, 300);
};
</script>
</body>
</html>
head 腳本直接操作 canvas:DOM 尚未就緒 → getElementById 回傳 null。解決:放在 window.onload、DOMContentLoaded 或 <script> 放在 </body> 前。getContext('2d'):同一 canvas 多次呼叫會回傳同一個 context 物件,無害但浪費;建議存變數複用。canvas.width = cssWidth * devicePixelRatio; canvas.style.width = cssWidth + 'px'; ctx.scale(dpr, dpr); 確保銳利度。canvas.getContext('webgl') 或 'webgl2' 取得 3D 上下文。canvas.transferControlToOffscreen() 移交給 Web Worker 離主執行緒渲染(需 OffscreenCanvas 支援)。掌握 Canvas 建立與上下文取得,是所有 Canvas 2D 繪圖、遊戲開發、圖表視覺化、圖像處理的起點。