arc方法是Canvas中绑制圆弧和圆形的核心方法。它可以绑制完整的圆,也可以绑制任意角度的圆弧。
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)
| 参数 | 类型 | 说明 |
|---|---|---|
| x | number | 圆心x坐标 |
| y | number | 圆心y坐标 |
| radius | number | 圆的半径 |
| startAngle | number | 起始角度(弧度) |
| endAngle | number | 结束角度(弧度) |
| anticlockwise | boolean | 是否逆时针绑制,默认false |
Canvas使用弧度制,角度从右侧(3点钟方向)开始,顺时针增加:
270° (3π/2)
│
│
180° ──────┼────── 0°
(π) │ (0)
│
│
90° (π/2)
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')
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()