arc() 是 Canvas 繪製圓、圓弧、扇形、圓環的核心方法。本文深度解析其六個參數、弧度制轉換、順逆時針方向、常見組合模式(扇形/圓環/圓角矩形)與避坑指南。
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)
| 參數 | 類型 | 說明 |
|---|---|---|
| x, y | Number | 圓心座標 |
| radius | Number ≥ 0 | 半徑 |
| startAngle | Number | 起始弧度(從 x 軸正方向逆時針) |
| endAngle | Number | 結束弧度 |
| anticlockwise | Boolean | true=逆時針,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° 圓弧。
// 同樣 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()
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+)。
Canvas 座標系:原點左上,X 向右,Y 向下。這導致:
anticlockwise=false)Path2D 對象復用 ctx.stroke(path)drawImage 繪製預渲染圖片、或 WebGL Point SpritesarcTo 參數理解難度大,圓角矩形優先用 roundRect 或手寫 arc 組合
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 繪圖進階的必經之路。