萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Canvas 元素建立完整教學:從基本屬性到繪圖環境初始化

<canvas> 是 HTML5 核心繪圖容器,本身不具繪圖能力,需透過 JavaScript 取得 CanvasRenderingContext2D(2D)或 WebGLRenderingContext(3D)上下文才能繪圖。本文從最基礎的標籤屬性、取得上下文、尺寸與 CSS 像素的關係、備用內容處理,建立完整的 Canvas 入門知識庫。

Canvas 標籤必要屬性

屬性說明預設值建議
width畫布實際像素寬度(繪圖緩衝區寬度)300必須以屬性或 JS 明確設定,勿只靠 CSS
height畫布實際像素高度150同上
id供 JS 選取—建議加上

關鍵概念:畫布尺寸 vs CSS 尺寸

<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 → 被拉大顯示 → **模糊失真**。

取得 2D 繪圖上下文

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>

常見新手錯誤與解決

  1. 在 head 腳本直接操作 canvas:DOM 尚未就緒 → getElementById 回傳 null。解決:放在 window.onload、DOMContentLoaded 或 <script> 放在 </body> 前。
  2. 混淆 width/height 屬性與 CSS width/height:導致模糊或座標計算錯誤。原則:**屬性決定緩衝區解析度,CSS 決定顯示大小**。
  3. 重複呼叫 getContext('2d'):同一 canvas 多次呼叫會回傳同一個 context 物件,無害但浪費;建議存變數複用。
  4. 未處理高 DPI (Retina):canvas.width = cssWidth * devicePixelRatio; canvas.style.width = cssWidth + 'px'; ctx.scale(dpr, dpr); 確保銳利度。

擴充:WebGL / OffscreenCanvas

  • canvas.getContext('webgl') 或 'webgl2' 取得 3D 上下文。
  • canvas.transferControlToOffscreen() 移交給 Web Worker 離主執行緒渲染(需 OffscreenCanvas 支援)。

掌握 Canvas 建立與上下文取得,是所有 Canvas 2D 繪圖、遊戲開發、圖表視覺化、圖像處理的起點。

copyright © 萬盛學電腦網 all rights reserved