<template>
  <view>
    <canvas class="drawing" id="tablet" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas>
    <button @click="doClear()">清空</button>
  </view>
</template>

<script>
  type Point = {
    x : number
    y : number
  };

  export default {
    data() {
      return {
        lastPointX: 0,
        lastPointY: 0,
        offsetX: 0,
        offsetY: 0,
        renderingContext: null as CanvasRenderingContext2D | null,
      }
    },
    onReady() {
      uni.createCanvasContextAsync({
        id: 'tablet',
        // component: this,
        success: (context : CanvasContext) => {
          console.log('success');
          this.renderingContext = context.getContext('2d')!;
          const canvas = this.renderingContext!.canvas;

          const dpr = uni.getWindowInfo().pixelRatio;
          canvas.width = canvas.offsetWidth * dpr
          canvas.height = canvas.offsetHeight * dpr
          this.renderingContext!.scale(dpr, dpr)

          // #ifndef MP
          const elRect = canvas.getBoundingClientRect()
          this.offsetX = elRect.left
          this.offsetY = elRect.top
          // #endif
        }
      })
    },
    methods: {
      touchStart(event : TouchEvent) {
        const position = this.getPosition(event)
        this.lastPointX = position.x
        this.lastPointY = position.y
      },
      touchMove(event : TouchEvent) {
        const position = this.getPosition(event)
        const x = position.x
        const y = position.y

        const ctx = this.renderingContext!
        ctx.lineWidth = 5
        ctx.lineCap = "round"
        ctx.lineJoin = "round"
        ctx.beginPath()
        ctx.moveTo(this.lastPointX, this.lastPointY)
        ctx.lineTo(x, y)
        ctx.stroke()

        this.lastPointX = x
        this.lastPointY = y
      },
      touchEnd(_ : TouchEvent) {
      },
      doClear() {
        if (this.renderingContext != null) {
          this.renderingContext!.clearRect(0, 0, this.renderingContext!.canvas.width, this.renderingContext!.canvas.height)
        }
      },
      getPosition(event : TouchEvent) : Point {
        const touch = event.touches[0]
        // #ifndef MP-WEIXIN
        return {
          x: touch.clientX - this.offsetX,
          y: touch.clientY - this.offsetY
        } as Point
        // #endif

        // #ifdef MP-WEIXIN
        return {
          x: touch.x,
          y: touch.y
        } as Point
        // #endif
      }
    }
  }
</script>

<style>
  .drawing {
    width: 100%;
    height: 500px;
    background-color: lightgray;
    margin-bottom: 15px;
  }
</style>
