VueでKonva.jsとcanvasを使ってお絵描き(その2)


その1はこちら

キャンバスに画像を表示する

親のCallCanvas.vueから、子のFreeDrawing.vueに画像ファイルパスを渡して、それをキャンバスに表示してみます。

まず、親のCallCanvas.vue。
親のテンプレートに記載したFreeDrawingタグに、子のpropsに定義した「backgroundImage」を追記し、
そこに値を指定します。
今回は算出プロパティ「imageFile」を用意し、それを値に指定してます。
(require()を使って渡さないと画像を表示できないとこでハマりました。。。)

src/paint.CallCanvas.vue
<template>
    <div>
        ...
        ..
        .
        <FreeDrawing 
          :backgroundImage="imageFile"
        />
    </div>
</template>

<script>
import FreeDrawing from './FreeDrawing.vue'

export default {
  name: 'CallCanvas',
  ...
  ..
  .
  computed: {
    imageFile: function () {
      return require('../assets/reiwa.png');
    }
  }
}
...
..
.

次に子のFreeDrawing.vue

FreeDrawing.vue
<template>
  <div>
    <div ref="container">
      <canvas
        :width="width/2"
        :height="height/2"
        ref="canvas">
      </canvas>
    </div>
  </div>
</template>

<script>
import Konva from 'konva'

export default {
  ...
  ..
  .
  data: () => ({
    ...
    ..
    .
    /** 追加 */
    imageObj: null,
    backgroundLayer: null,
    backgroundImageScope: null
  }),
  mounted: function () {
    ...
    ..
    .
    /** 追加 */
    this.imageObj = new Image()
    this.imageObj.addEventListener('load', this.imageOnload)
    this.imageObj.src = this.backgroundImage
  },
  methods: {
    ...
    ..
    .
    /** 追加 */
    imageOnload: function () {
      // 背景レイヤ
      this.backgroundLayer = new Konva.Layer()

      // 背景イメージ(xとy座標はthis.drawingScopeと同じにする)
      this.backgroundImageScope = new Konva.Image({
        image: this.imageObj,
        x: this.width / 4,
        y: 5,
        width: this.canvas.width,
        height: this.canvas.height
      })

      // 背景レイヤに背景イメージを追加
      this.backgroundLayer.add(this.backgroundImageScope)
      this.stage.add(this.backgroundLayer)

      // 背景イメージを最背面に移動。これをしないとペンの描画が画像の下に潜ってしまう。
      this.backgroundLayer.moveToBottom()
    }
  },
  ...
  ..
  .
}
</script>

サーバー起動して確かめます。

表示できました、描画もできます。
また、画像がキャンバスサイズより大きい場合は、キャンバスサイズに縮小されますし、
小さい場合は拡大されます。

その3はモードをペンと消しゴムで切り替えられるようにしてみます。
その3:モード および ペンの色切り替え、キャンバスのクリア