canvas/path.go

80 lines
1.5 KiB
Go

package canvas
import (
"image"
"math"
)
// path 路径结构
type path struct {
points []image.Point
start image.Point
}
// BeginPath 开始新路径
func (c *Context) BeginPath() {
c.path = &path{}
}
// MoveTo 移动到指定位置
func (c *Context) MoveTo(x, y float64) {
pt := c.transformPoint(x, y)
c.path.points = append(c.path.points, pt)
c.path.start = pt
}
// LineTo 绘制线段到指定位置
func (c *Context) LineTo(x, y float64) {
if len(c.path.points) == 0 {
c.MoveTo(x, y)
return
}
c.path.points = append(c.path.points, c.transformPoint(x, y))
}
// Rect 绘制矩形路径
func (c *Context) Rect(x, y, width, height float64) {
c.MoveTo(x, y)
c.LineTo(x+width, y)
c.LineTo(x+width, y+height)
c.LineTo(x, y+height)
c.ClosePath()
}
// Arc 绘制圆弧路径
func (c *Context) Arc(x, y, radius, startAngle, endAngle float64) {
// 确保角度在0-2π之间
for startAngle < 0 {
startAngle += 2 * math.Pi
}
for endAngle < 0 {
endAngle += 2 * math.Pi
}
// 确定步数
angleRange := endAngle - startAngle
if angleRange < 0 {
angleRange += 2 * math.Pi
}
steps := int(math.Ceil(angleRange * 10)) // 每弧度10步
for i := 0; i <= steps; i++ {
t := float64(i) / float64(steps)
angle := startAngle + t*angleRange
px := x + radius*math.Cos(angle)
py := y + radius*math.Sin(angle)
if i == 0 {
c.MoveTo(px, py)
} else {
c.LineTo(px, py)
}
}
}
// ClosePath 闭合路径
func (c *Context) ClosePath() {
if len(c.path.points) > 0 {
c.LineTo(float64(c.path.start.X), float64(c.path.start.Y))
}
}