65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
package canvas
|
|
|
|
import (
|
|
"image"
|
|
"image/color"
|
|
"image/draw"
|
|
|
|
"golang.org/x/image/font"
|
|
)
|
|
|
|
// Context 画布上下文
|
|
type Context struct {
|
|
img *image.RGBA // 底层图像
|
|
state *contextState // 当前状态
|
|
states []*contextState // 状态栈
|
|
path *path // 当前路径
|
|
}
|
|
|
|
type contextState struct {
|
|
fillStyle interface{} // color.Color 或 Gradient
|
|
strokeStyle interface{} // color.Color 或 Gradient
|
|
lineWidth float64
|
|
globalAlpha float64
|
|
transform [6]float64 // 变换矩阵 [a, b, c, d, e, f]
|
|
fontFace font.Face
|
|
textAlign string
|
|
textBaseline string
|
|
shadowColor color.Color
|
|
shadowOffsetX float64
|
|
shadowOffsetY float64
|
|
shadowBlur float64
|
|
}
|
|
|
|
// NewContext 创建新的画布上下文
|
|
func NewContext(width, height int) *Context {
|
|
img := image.NewRGBA(image.Rect(0, 0, width, height))
|
|
// 白色背景
|
|
draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
|
|
|
|
initialState := &contextState{
|
|
fillStyle: color.Black,
|
|
strokeStyle: color.Black,
|
|
lineWidth: 1.0,
|
|
globalAlpha: 1.0,
|
|
transform: [6]float64{1, 0, 0, 1, 0, 0}, // 单位矩阵
|
|
textAlign: "start",
|
|
textBaseline: "alphabetic",
|
|
shadowColor: color.RGBA{0, 0, 0, 128},
|
|
shadowOffsetX: 0,
|
|
shadowOffsetY: 0,
|
|
shadowBlur: 0,
|
|
}
|
|
return &Context{
|
|
img: img,
|
|
state: initialState,
|
|
states: []*contextState{},
|
|
path: &path{},
|
|
}
|
|
}
|
|
|
|
// Image 返回底层图像
|
|
func (c *Context) Image() image.Image {
|
|
return c.img
|
|
}
|