萬盛學電腦網

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

Canvas 圓弧繪製完全指南:arc 參數詳解、弧度制、方向控制與實戰技巧

arc() 是 Canvas 繪製圓、圓弧、扇形、圓環的核心方法。本文深度解析其六個參數、弧度制轉換、順逆時針方向、常見組合模式(扇形/圓環/圓角矩形)與避坑指南。

API 簽名


ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)
參數類型說明
x, yNumber圓心座標
radiusNumber ≥ 0半徑
startAngleNumber起始弧度(從 x 軸正方向逆時針)
endAngleNumber結束弧度
anticlockwiseBooleantrue=逆時針,false=順時針(默認)

弧度制核心公式


弧度 = 角度 × Math.PI / 180
// 常用角度對照
0°    = 0
90°   = Math.PI/2   (π/2)
180°  = Math.PI     (π)
270°  = 3*Math.PI/2 (3π/2)
360°  = 2*Math.PI   (2π)

切記:Canvas 所有角度 API 均使用弧度,非角度。

基礎繪製示例

完整圓


ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2); // 0 到 2π
ctx.fillStyle = 'blue';
ctx.fill(); // 實心圓
// 或
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.stroke(); // 空心圓

四分之一圓弧(順時針)


ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI/2, false); // 0 → 90°
ctx.stroke();

從 3 點鐘方向畫到 12 點鐘方向(Canvas Y 軸向下)。

四分之三圓弧(逆時針)


ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI/2, true); // 逆時針 0 → 90°
ctx.stroke();

繪製除第一象限外的 270° 圓弧。

方向參數 anticlockwise 詳細解析


// 同樣 start=0, end=π/2 (90°)
anticlockwise=false: 從 0° 順時針 畫到 90°  → 第一象限(右上)
anticlockwise=true:  從 0° 逆時針 畫到 90° → 第二三四象限(左上、左下、右下)

記憶口訣:false 走短路,true 走長路(角度差 < π 時)。

實戰組合模式

扇形


function drawSector(ctx, cx, cy, r, startDeg, endDeg, fillColor) {
  const sA = startDeg * Math.PI/180;
  const eA = endDeg * Math.PI/180;
  ctx.beginPath();
  ctx.moveTo(cx, cy);           // 移至圓心
  ctx.arc(cx, cy, r, sA, eA);   // 畫弧
  ctx.closePath();              // 自動連回圓心
  ctx.fillStyle = fillColor;
  ctx.fill();
}

圓環


function drawRing(ctx, cx, cy, outerR, innerR, fillColor) {
  ctx.beginPath();
  ctx.arc(cx, cy, outerR, 0, Math.PI*2);
  ctx.arc(cx, cy, innerR, 0, Math.PI*2, true); // 逆時針內圓形成孔洞
  ctx.fillStyle = fillColor;
  ctx.fill('evenodd'); // 非零環繞規則 / evenodd 規則
}

或用 lineWidth:ctx.arc(cx,cy,r,0,2π); ctx.lineWidth=20; ctx.strokeStyle=color; ctx.stroke()

圓角矩形(傳統 arcTo 方案)


function roundRect(ctx, x, y, w, h, r) {
  ctx.beginPath();
  ctx.moveTo(x+r, y);
  ctx.arcTo(x+w, y, x+w, y+h, r); // 右上角
  ctx.arcTo(x+w, y+h, x, y+h, r); // 右下角
  ctx.arcTo(x, y+h, x, y, r);     // 左下角
  ctx.arcTo(x, y, x+w, y, r);     // 左上角
  ctx.closePath();
}

現代瀏覽器推薦直接用 ctx.roundRect(x,y,w,h,r)(Chrome 107+、Firefox 105+、Safari 16.4+)。

座標系陷阱:Y 軸向下

Canvas 座標系:原點左上,X 向右,Y 向下。這導致:

  • 標準數學中逆時針為正,Canvas 中 順時針為正(anticlockwise=false)
  • 90° (π/2) 指向 6 點鐘方向(下),而非 12 點鐘
  • 繪製時鐘/儀表盤需將角度 -90° ( -π/2 ) 對齊 12 點鐘

性能與最佳實踐

  • 重複相同圓/弧:構建 Path2D 對象復用 ctx.stroke(path)
  • 大量粒子圓:考慮 drawImage 繪製預渲染圖片、或 WebGL Point Sprites
  • 避免在動畫循環中重複創建漸變/模式對象,預創建緩存
  • arcTo 參數理解難度大,圓角矩形優先用 roundRect 或手寫 arc 組合

arcTo 補充:切線圓弧


ctx.arcTo(x1, y1, x2, y2, radius)
// 從當前點 向 (x1,y1) 方向畫線,在 (x1,y1) 和 (x2,y2) 形成的角 內切半徑 radius 的圓弧
// 終點落在 (x1,y1) 到 (x2,y2) 的線段上

主要用於圓角矩形、路徑平滑連接。理解難度較高,實際開發多用 arc 組合或 roundRect。

總結

arc() 看似簡單六參數,實則蘊含座標系、弧度制、方向控制、路徑組合等核心概念。熟練掌握「弧度轉換、方向選擇、moveTo 起點設置、closePath 閉合、fill/stroke 執行」完整鏈路,是 Canvas 繪圖進階的必經之路。

copyright © 萬盛學電腦網 all rights reserved