萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

HTML5 Canvas 繪製圓形完整指南:arc() 方法與路徑閉合

前言

Canvas 無直接畫圓方法,使用 `arc(x, y, radius, startAngle, endAngle, anticlockwise)` 繪製圓弧,`startAngle=0, endAngle=2*Math.PI` 即為完整圓形。

arc() 參數詳解

ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)
  • x, y:圓心座標。
  • radius:半徑(非負)。
  • startAngle, endAngle:弧度制(非角度),0 為 3 點鐘方向,順時針增加。
  • anticlockwise(可選):`true` 逆時針,`false` 順時針(預設)。

角度轉弧度

const degToRad = deg => deg * Math.PI / 180;
// 90° = Math.PI/2, 180° = Math.PI, 360° = 2*Math.PI

完整範例:描邊圓形

<!DOCTYPE html>
<html>
<body>
  <canvas id="myCanvas" width="300" height="200" style="border:1px solid #ddd"></canvas>
  <script>
  const ctx = document.getElementById('myCanvas').getContext('2d');

  ctx.beginPath();
  ctx.arc(150, 100, 60, 0, 2 * Math.PI); // 完整圓
  ctx.strokeStyle = '#e74c3c';
  ctx.lineWidth = 3;
  ctx.stroke();

  // 填滿圓形
  ctx.beginPath();
  ctx.arc(150, 100, 40, 0, 2 * Math.PI);
  ctx.fillStyle = 'rgba(231, 76, 60, 0.3)';
  ctx.fill();
  </script>
</body>
</html>

進階:扇形與圓弧

// 扇形 (Pac-Man)
ctx.beginPath();
ctx.moveTo(150, 100); // 移至圓心
ctx.arc(150, 100, 60, degToRad(30), degToRad(330));
ctx.closePath(); // 連回圓心
ctx.fillStyle = '#f39c12';
ctx.fill();

// 圓弧 (不閉合)
ctx.beginPath();
ctx.arc(150, 100, 80, degToRad(0), degToRad(90));
ctx.strokeStyle = '#3498db';
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.stroke();

常見錯誤

  • 忘記 `beginPath()` 導致路徑疊加、連線錯誤。
  • 角度未轉弧度(傳入 360 而非 `2*Math.PI`)。
  • 半徑為負值不會報錯但不繪製。

總結

`arc()` 是 Canvas 畫圓/圓弧/扇形的核心方法。記住「弧度制、順時針、需 beginPath」,並善用 `degToRad` 輔助函式提升可讀性。

copyright © 萬盛學電腦網 all rights reserved