arc 绘制圆弧

arc方法是Canvas中绑制圆弧和圆形的核心方法。它可以绑制完整的圆,也可以绑制任意角度的圆弧。

arc方法语法

ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)
参数类型说明
xnumber圆心x坐标
ynumber圆心y坐标
radiusnumber圆的半径
startAnglenumber起始角度(弧度)
endAnglenumber结束角度(弧度)
anticlockwiseboolean是否逆时针绑制,默认false

角度系统

Canvas使用弧度制,角度从右侧(3点钟方向)开始,顺时针增加:

        270° (3π/2)
           │
           │
180° ──────┼────── 0°
  (π)      │       (0)
           │
           │
        90° (π/2)

角度系统可视化

Canvas角度系统

绘制完整圆形

ctx.beginPath()
ctx.arc(100, 100, 50, 0, Math.PI * 2)
ctx.fillStyle = '#3498db'
ctx.fill()

绘制圆弧

// 四分之一圆弧
ctx.beginPath()
ctx.arc(100, 100, 50, 0, Math.PI / 2)
ctx.strokeStyle = '#e74c3c'
ctx.lineWidth = 3
ctx.stroke()

// 半圆弧
ctx.beginPath()
ctx.arc(200, 100, 50, 0, Math.PI)
ctx.stroke()

各种圆弧演示

四分之一弧

半圆弧

四分之三弧

扇形

顺时针与逆时针

顺时针(默认)

逆时针

绘制扇形

扇形需要连接圆心:

ctx.beginPath()
ctx.moveTo(100, 100)        // 移动到圆心
ctx.arc(100, 100, 50, 0, Math.PI / 2)
ctx.closePath()             // 闭合路径
ctx.fillStyle = '#9b59b6'
ctx.fill()

绘制圆环

使用两个方向相反的圆:

ctx.beginPath()
ctx.arc(100, 100, 50, 0, Math.PI * 2)
ctx.arc(100, 100, 30, 0, Math.PI * 2, true)  // 逆时针
ctx.fillStyle = '#3498db'
ctx.fill('evenodd')

圆环演示

使用evenodd填充规则绘制圆环

角度转弧度

function degToRad(degrees) {
  return degrees * Math.PI / 180
}

// 使用角度值
ctx.arc(100, 100, 50, degToRad(0), degToRad(90))

饼图示例

饼图示例

注意事项

半径必须为正

ctx.arc(100, 100, -50, 0, Math.PI * 2)  // 报错

arc会连接到当前点

ctx.beginPath()
ctx.moveTo(50, 50)
ctx.arc(150, 50, 30, 0, Math.PI * 2)
ctx.stroke()  // 会从(50,50)画线到圆弧起点

避免这个问题

ctx.beginPath()
ctx.arc(150, 50, 30, 0, Math.PI * 2)
ctx.stroke()

arc连接问题演示

❌ 错误:arc连接到当前点

✓ 正确:单独的路径