<canvas> 是 HTML5 新增的繪圖容器元素,本質是一個位圖畫布。本文詳細講解標籤屬性、正確寫法、JavaScript 獲取繪圖上下文、內容回退機制與新手常犯錯誤。
<canvas id="canvasOne" width="500" height="300">
Your browser does not support HTML5 Canvas.
</canvas>
| 屬性 | 類型 | 說明 | 默認值 |
|---|---|---|---|
| id | String | 唯一標識,JS 獲取元素用 | 無 |
| width | Number (CSS 像素) | 畫布寬度(內部像素網格寬) | 300 |
| height | Number (CSS 像素) | 畫布高度(內部像素網格高) | 150 |
<canvas>...</canvas>,不可 自閉合 <canvas />width="500",非 width="500px"
3. 內部內容作為回退:不支持 Canvas 的瀏覽器會顯示標籤內內容(文字、圖片、鏈接等)
4. CSS 尺寸 ≠ 畫布尺寸:CSS 控制顯示大小,屬性控制繪圖分辨率(詳見《Canvas 寬高設置陷阱》)
// 1. 獲取 Canvas 元素
const canvas = document.getElementById('canvasOne');
// 或 querySelector
const canvas = document.querySelector('#canvasOne');
// 2. 獲取 2D 渲染上下文
const ctx = canvas.getContext('2d');
// 3. 可選:獲取 WebGL 上下文
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
// 4. 可選:獲取 OffscreenCanvas/WebGL2 等
const offscreen = canvas.transferControlToOffscreen(); // Worker 中使用
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas App</title>
<style>
canvas { border: 1px solid #ccc; display: block; margin: 20px auto; }
</style>
</head>
<body>
<canvas id="app" width="800" height="600">
<p>您的瀏覽器不支持 HTML5 Canvas,請升級至現代瀏覽器。</p>
<p><a href="https://browsehappy.com/" target="_blank">查看推薦瀏覽器</a></p>
</canvas>
<script>
const canvas = document.getElementById('app');
if (!canvas || !canvas.getContext) {
// 已由瀏覽器自動顯示回退內容,這裡可做額外統計
return;
}
const ctx = canvas.getContext('2d');
// 高清屏適配
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
ctx.scale(dpr, dpr);
// 開始繪圖...
ctx.fillStyle = '#3498db';
ctx.fillRect(50, 50, 200, 100);
</script>
</body>
</html>
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
<canvas width="500px"> | 屬性值帶單位 | <canvas width="500"> |
<canvas /> | 自閉合標籤無效 | <canvas></canvas> |
| CSS 設 width/height 而不設屬性 | 默認 300×150 畫布被拉伸變形 | 屬性設邏輯尺寸,CSS 設顯示尺寸 |
canvas.getContext('3d') | 上下文類型錯誤 | '2d', 'webgl', 'webgl2', 'bitmaprenderer' |
| 獲取 ctx 後不檢查 null | 不支持時拋錯 | if (!ctx) return; |
| 在 head 中執行腳本獲取 canvas | DOM 未就緒,獲取 null | 腳本放 body 末尾或 defer/onload |
// 模式 1:多層疊加(背景層 + 動畫層 + UI 層)
<div class="canvas-stack">
<canvas id="bg-layer" width="800" height="600" style="position:absolute; z-index:1"></canvas>
<canvas id="game-layer" width="800" height="600" style="position:absolute; z-index:2"></canvas>
<canvas id="ui-layer" width="800" height="600" style="position:absolute; z-index:3"></canvas>
</div>
// 模式 2:離屏 Canvas 預渲染
const offscreen = document.createElement('canvas');
offscreen.width = 800; offscreen.height = 600;
const octx = offscreen.getContext('2d');
// 複雜靜態場景繪製到 offscreen...
// 主循環:ctx.drawImage(offscreen, 0, 0);
<canvas><p>圖表顯示銷售額:Q1 120萬,Q2 135萬...</p></canvas>aria-label、role="img"、aria-live正確添加 <canvas> 是 Canvas 開發的第一步。牢記「屬性定分辨率、CSS 定佈局、必須閉合標籤、回退內容不可少、獲取上下文必判空」,再配合高清屏適配模板,即可避開 90% 的初始化坑點,專注於核心繪圖邏輯。