萬盛學電腦網

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

Canvas 繪圖入門:空心圓、實心圓與組合繪製完整示例

Canvas 繪製圓形是圖形編程的基礎操作。本文通過完整代碼示例,演示如何繪製空心圓、實心圓及兩者組合,並解析關鍵 API 與繪製流程。

核心 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>

關鍵點解析

  1. 弧度制:arc 參數為弧度,0 到 2*Math.PI 為完整圓。切記不要傳 360(度數)。
  2. 路徑隔離:每組圖形用 beginPath() 開啟新路徑,防止樣式污染與路徑殘留。
  3. 繪製順序:組合圖形時,先 fill() 後 stroke(),否則描邊會被填充覆蓋一半。
  4. 坐標系:Canvas 原點 (0,0) 在左上角,x 向右,y 向下。

進階技巧:漸變與陰影

// 線性漸變填充
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() 導致路徑疊加、樣式混亂
  • 角度單位混淆(度 vs 弧度)
  • closePath() 不會自動填充/描邊,必須顯式調用 fill()/stroke()
  • 重複設置 fillStyle/strokeStyle 時未重置,影響後續繪製

掌握圓形繪製是 Canvas 進階的基石。建議在 CodePen 或本地頁面動手實驗,嘗試不同半顏色、線寬、漸變組合,建立直觀的繪圖心智模型。

copyright © 萬盛學電腦網 all rights reserved