一个简单的绘图板

【OpenHarmony应用开发】eTS实现Canvas绘图板_eTS

快速体验ets canvas绘图

@Entry
@Component
struct Index {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
@State x: number = 0
@State y: number = 0
@State startX: number = 0
@State startY: number = 0
private colors = ['#000000','#ff0000','#ffff00','#0000ff','#ff00ff']

build() {
Stack() {
Canvas(this.ctx)
.width('100%')
.height('100%')
.onReady(() => {
this.ctx.lineWidth = 6
this.ctx.strokeStyle = '#000000'
this.ctx.lineCap = 'round'
this.ctx.lineJoin = 'round'
})
.onTouch(e => {
let pos = e.touches[0]
if (!pos) return

if (e.type == TouchType.Down) {
this.ctx.restore()
this.ctx.beginPath()
this.startX = pos.x
this.startY = pos.y
} else if (e.type == TouchType.Move) {
this.x = pos.x
this.y = pos.y

this.ctx.moveTo(this.startX, this.startY)
this.ctx.lineTo(this.x, this.y)
this.ctx.stroke()

this.startX = pos.x
this.startY = pos.y
} else if (e.type == TouchType.Up) {
this.ctx.save()
}
})

Flex({justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center}) {
ForEach(this.colors,(color)=>{
Row(){}.backgroundColor(color).width(50).height(50)
.onClick(()=>{
this.ctx.restore()
this.ctx.strokeStyle = color
})
})
}
.height(50)
.width('100%')
.backgroundColor('rgba(0,0,0,0.5)')
.position({
x: 0,
y: 0
})
}
.width('100%')
.height('100%')
}
}

参考文档地址:
https://gitee.com/openharmony/docs/blob/5654c2b940ab3e2f4f0baf435e630c4ef3536428/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md
https://gitee.com/openharmony/docs/blob/5654c2b940ab3e2f4f0baf435e630c4ef3536428/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md