Canvas 繪製圓形是圖形編程的基礎操作。本文通過完整代碼示例,演示如何繪製空心圓、實心圓及兩者組合,並解析關鍵 API 與繪製流程。
arc(x, y, r, startAngle, endAngle, anticlockwise):創建圓弧/圓路徑stroke():描邊(空心)fill():填充(實心)beginPath()/closePath():路徑管理lineWidth、strokeStyle、fillStyle:樣式屬性<canvas id="canvas" width="500" height="500" style="background: #ffff00"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 1. 空心圓
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2); // 角度用弧度:360° = 2π
ctx.lineWidth = 5;
ctx.strokeStyle = 'green';
ctx.stroke();
ctx.closePath();
// 2. 實心圓
ctx.beginPath();
ctx.arc(200, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
// 3. 空心+實心組合(同心圓效果)
ctx.beginPath();
ctx.arc(300, 300, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill(); // 先填充
ctx.strokeStyle = 'green';
ctx.stroke(); // 再描邊
ctx.closePath();
</script>
arc 參數為弧度,0 到 2*Math.PI 為完整圓。切記不要傳 360(度數)。beginPath() 開啟新路徑,防止樣式污染與路徑殘留。fill() 後 stroke(),否則描邊會被填充覆蓋一半。// 線性漸變填充
const gradient = ctx.createLinearGradient(150, 50, 250, 150);
gradient.addColorStop(0, '#ff0000');
gradient.addColorStop(1, '#ffff00');
ctx.fillStyle = gradient;
// 陰影效果
ctx.shadowColor = 'rgba(0,0,0,0.5)';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
beginPath() 導致路徑疊加、樣式混亂closePath() 不會自動填充/描邊,必須顯式調用 fill()/stroke()fillStyle/strokeStyle 時未重置,影響後續繪製掌握圓形繪製是 Canvas 進階的基石。建議在 CodePen 或本地頁面動手實驗,嘗試不同半顏色、線寬、漸變組合,建立直觀的繪圖心智模型。