nuxtでサイン入力画面を作る


サイン入力画面の作り方

サイン入力画面の作り方でつまづいたところがあるので記事に残します。

style, template, styleに分けて書きます

style

<style scoped>
#sign {
  border: #6f6f6f 1px solid;
  display: block;
}
</style>

canvasのサイズをcssで指定しない

template

<template>
  <section>
    <h1>手書きサイン入力デモ</h1>
    <canvas id="sign" width="600" height="150" />
    <el-button @click="clear">クリア</el-button>
  </section>
</template>

canvasのサイズはtemplateで指定する
こうしないとマウスでサイン入力時に画面とサインがずれる

script

<script>
export default {
  data() {
    return {
      move: false,
      ox: 0,
      oy: 0,
      x: 0,
      y: 0
    }
  },
  mounted() {
    const canvas = document.querySelector('#sign')
    canvas.addEventListener('touchstart', this.start, false)
    canvas.addEventListener('touchmove', this.draw, false)
    canvas.addEventListener('touchend', this.stop, false)
    canvas.addEventListener('mousedown', this.start, false)
    canvas.addEventListener('mousemove', this.draw, false)
    canvas.addEventListener('mouseup', this.stop, false)
    canvas.addEventListener('mouseout', this.stop, false)

    const context = canvas.getContext('2d')
    context.strokeStyle = '#000000'
    context.lineWidth = 2
    context.lineJoin = 'round'
    context.lineCap = 'round'
  },
  methods: {
    start(event) {
      this.move = true
      const canvas = document.querySelector('#sign')
      this.ox = (event.clientX || event.touches[0].pageX) - canvas.offsetLeft
      this.oy = (event.clientY || event.touches[0].pageY) - canvas.offsetTop
    },
    draw(event) {
      if (this.move) {
        const canvas = document.querySelector('#sign')
        this.x = (event.clientX || event.touches[0].pageX) - canvas.offsetLeft
        this.y = (event.clientY || event.touches[0].pageY) - canvas.offsetTop
        this.drawLine()
        this.ox = this.x
        this.oy = this.y
      }
    },
    stop(event) {
      this.move = false
    },
    drawLine() {
      const canvas = document.querySelector('#sign')
      const context = canvas.getContext('2d')
      context.beginPath()
      context.moveTo(this.ox, this.oy)
      context.lineTo(this.x, this.y)
      context.stroke()
      context.closePath()
    },
    clear() {
      const canvas = document.querySelector('#sign')
      const context = canvas.getContext('2d')
      context.fillStyle = '#ffffff'
      context.fillRect(0, 0, canvas.width, canvas.height)
    }
  }
}
</script>

参照

HTML5のcanvasに手書きやマウスのドラッグで絵を書く