CanvasRenderingContext2D: arc() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

CanvasRenderingContext2D.arc() 方法是 Canvas 2D API 的一部分,用於向當前子路徑新增一個圓形弧線。

語法

js
arc(x, y, radius, startAngle, endAngle)
arc(x, y, radius, startAngle, endAngle, counterclockwise)

arc() 方法會建立一個以 (x, y) 為中心,半徑為 radius 的圓形弧線。路徑從 startAngle 開始,到 endAngle 結束,並根據 counterclockwise 引數(預設為順時針)的方向繪製。

引數

x

弧線中心的水平座標。

y

弧線中心的垂直座標。

半徑

弧線的半徑。必須是正數。

startAngle

弧線開始的角度(以弧度為單位),從正 x 軸開始測量。

endAngle

弧線結束的角度(以弧度為單位),從正 x 軸開始測量。

counterclockwise 可選

一個可選的布林值。如果為 true,則在起始角度和結束角度之間逆時針繪製弧線。預設值為 false(順時針)。

返回值

無(undefined)。

示例

繪製一個完整的圓

此示例使用 arc() 方法繪製了一個完整的圓。

HTML

html
<canvas></canvas>

JavaScript

該弧線的 x 座標為 100,y 座標為 75,半徑為 50。要繪製一個完整的圓,弧線從 0 弧度(0°)開始,到 2π 弧度(360°)結束。

js
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();

結果

演示不同的形狀

此示例繪製了各種形狀,以展示 arc() 的功能。

js
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

// Draw shapes
for (let i = 0; i <= 3; i++) {
  for (let j = 0; j <= 2; j++) {
    ctx.beginPath();
    let x = 25 + j * 50; // x coordinate
    let y = 25 + i * 50; // y coordinate
    let radius = 20; // Arc radius
    let startAngle = 0; // Starting point on circle
    let endAngle = Math.PI + (Math.PI * j) / 2; // End point on circle
    let counterclockwise = i % 2 === 1; // Draw counterclockwise

    ctx.arc(x, y, radius, startAngle, endAngle, counterclockwise);

    if (i > 1) {
      ctx.fill();
    } else {
      ctx.stroke();
    }
  }
}

結果

規範

規範
HTML
# dom-context-2d-arc-dev

瀏覽器相容性

另見