vue-konva 如何开始绘图

vue-konva how start drawing

需要在 mousedown 事件发生时在舞台元素中开始绘画。我在官方文档中有带有js的模板和示例。如何使用 Line 并开始绘制?

<template>
  <v-stage
    ref="stage"
    :config="stageSize"
    @mousedown="handleMousedown"
   
  >
    <v-layer ref="layer">
    </v-layer>
  </v-stage>
</template>

export default {
  data() {
    return {
      stageSize: {
        width: width,
        height: height,
      },
      text: "",
      isDrawing: false,
    };
  },
  methods: {
    handleMousedown() {
      console.log("test");
      this.isDrawing = true;
        
    }
  },
};
</script> 

来自官方文档的例子

stage.on('mousedown touchstart', function (e) {
        isPaint = true;
        var pos = stage.getPointerPosition();
        lastLine = new Konva.Line({
          stroke: '#df4b26',
          strokeWidth: 5,
          globalCompositeOperation:
            mode === 'brush' ? 'source-over' : 'destination-out',
          // round cap for smoother lines
          lineCap: 'round',
          // add point twice, so we have some drawings even on a simple click
          points: [pos.x, pos.y, pos.x, pos.y],
        });
        layer.add(lastLine);
      });

使用“vue-way”:

<template>
  <div>
    <v-stage
      ref="stage"
      :config="configKonva"
      @mousedown="handleMouseDown"
      @mousemove="handleMouseMove"
      @mouseup="handleMouseUp"
    >
      <v-layer ref="layer">
        <v-line
          v-for="line in lines"
          :key="line.id"
          :config="{
            stroke: 'black',
            points: line.points,
          }"
        />
      </v-layer>
    </v-stage>
  </div>
</template>

<script>
const width = window.innerWidth;
const height = window.innerHeight;
export default {
  data() {
    return {
      lines: [],
      isDrawing: false,
      configKonva: {
        width: width,
        height: height,
      },
    };
  },
  methods: {
    handleMouseDown(e) {
      this.isDrawing = true;
      const pos = e.target.getStage().getPointerPosition();
      this.lines = [...this.lines, { points: [pos.x, pos.y] }];
    },
    handleMouseMove(e) {
      // no drawing - skipping
      if (!this.isDrawing) {
        return;
      }
      const stage = e.target.getStage();
      const point = stage.getPointerPosition();
      let lastLine = this.lines[this.lines.length - 1];
      // add point
      lastLine.points = lastLine.points.concat([point.x, point.y]);

      // replace last
      this.lines.splice(this.lines.length - 1, 1, lastLine);
    },

    handleMouseUp() {
      this.isDrawing = false;
    },
  },
};
</script>

<style>
body {
  margin: 0;
  padding: 0;
}
</style>

演示:https://codesandbox.io/s/vue-konva-free-drawing-ux2uy?file=/src/App.vue