<canvas> 是 HTML5 新增的**位圖繪圖面板**,本身無繪圖能力,必須通過 JavaScript 獲取其「繪圖上下文」調用 API 繪製。理解三者關係:
<canvas id="c" width="640" height="480"> 容器;document.getElementById('c') 獲取元素節點;canvas.getContext('2d') 獲取繪圖上下文,調用 fillRect、arc 等方法繪圖。
<!DOCTYPE html>
<html><body>
<canvas id="canvas" width="640" height="480">
您的瀏覽器不支持 Canvas,請升級。
</canvas>
<script src="script.js"></script>
</body></html>
// script.js
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 設置畫筆(描邊)與填充顏色
ctx.strokeStyle = 'black'; // 畫筆顏色
ctx.fillStyle = 'yellow'; // 填充顏色
Canvas 無直接畫圓方法,使用路徑構建:
ctx.beginPath(); // 開始新路徑
ctx.arc(320, 240, 200, 0, Math.PI * 2); // 圓心(320,240),半徑200,0到2π完整圓弧
ctx.fill(); // 填充內部
ctx.stroke(); // 描邊
ctx.closePath(); // 關閉路徑(良好習慣)
arc(x, y, radius, startAngle, endAngle) 角度單位為**弧度**,Math.PI * 2 = 360°。
ctx.fillStyle = 'white'; // 切換填充色
// 左眼
ctx.beginPath();
ctx.arc(270, 175, 30, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.closePath();
// 右眼
ctx.beginPath();
ctx.arc(370, 175, 30, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.fillStyle = 'red'; // 嘴巴填充紅色
ctx.beginPath();
// 圓心(320,240),半徑150,從0到-π(順時針繪製上半圓弧)
ctx.arc(320, 240, 150, 0, -Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'black';
// 臉
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.arc(320, 240, 200, 0, Math.PI * 2);
ctx.fill(); ctx.stroke(); ctx.closePath();
// 眼睛
ctx.fillStyle = 'white';
[270, 370].forEach(x => {
ctx.beginPath();
ctx.arc(x, 175, 30, 0, Math.PI * 2);
ctx.fill(); ctx.stroke(); ctx.closePath();
});
// 嘴
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(320, 240, 150, 0, -Math.PI);
ctx.fill(); ctx.stroke(); ctx.closePath();

requestAnimationFrame 實現眨眼、嘴巴張合動畫;Math.atan2 計算角度);ctx.quadraticCurveTo 繪製貝茲曲線嘴巴,表現更多情緒。| 概念 | 關鍵點 |
|---|---|
| Canvas 元素 | 僅是容器,需指定 width/height 屬性(非 CSS),否則默認 300×150 並被拉伸模糊 |
| 繪圖上下文 | getContext('2d') 返回 CanvasRenderingContext2D,包含所有繪圖方法 |
| 路徑 | beginPath → 繪製指令 → fill/stroke → closePath,狀態機模式 |
| 顏色狀態 | fillStyle/strokeStyle 為上下文屬性,修改後對後續繪製生效 |
| 坐標系 | 原點(0,0)在左上角,X 右正,Y 下正,單位像素 |
恭喜!你已完成第一個 Canvas 繪圖程序。這個笑臉雖簡單,但蘊含了「聲明式 HTML 容器 + 命令式 JS 繪圖」的核心範式。繼續探索 drawImage、getImageData、變換矩陣、動畫循環,解鎖 Canvas 的無限可能。