【甜甜酱OH实践】简单的canvas绘图板 原创

发布于 2022-4-14 14:37
浏览
5收藏

一个简单的绘图板
【甜甜酱OH实践】简单的canvas绘图板-开源基础软件社区

快速体验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

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
7
收藏 5
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐