Skip to main content

如何使用 Vue 和 Konva 监听画布形状上的事件?

使用 vue-konva,您可以轻松监听用户输入事件(clickdblclickmouseovertapdbltaptouchstart 等等)以及拖放事件(dragstartdragmovedragend)。

有关事件的完整列表,请查看 on() 方法文档

说明:将鼠标移到三角形上以查看坐标。将鼠标移出以查看 mouseout 事件。

<template>
  <v-stage ref="stage" :config="stageSize">
    <v-layer ref="layer">
      <v-regular-polygon
        @mousemove="handleMouseMove"
        @mouseout="handleMouseOut"
        :config="{
          x: 80,
          y: 120,
          sides: 3,
          radius: 80,
          fill: '#00D2FF',
          stroke: 'black',
          strokeWidth: 4
        }"
      />
      <v-text ref="text" :config="{
        x: 10,
        y: 10,
        fontFamily: 'Calibri',
        fontSize: 24,
        text: text,
        fill: 'black'
      }" />
    </v-layer>
  </v-stage>
</template>

<script>
const width = window.innerWidth;
const height = window.innerHeight;

export default {
  data() {
    return {
      stageSize: {
        width: width,
        height: height
      },
      text: ''
    };
  },
  methods: {
    writeMessage(message) {
      this.text = message;
    },
    handleMouseOut(event) {
      this.writeMessage('鼠标移出三角形');
    },
    handleMouseMove(event) {
      const mousePos = this.$refs.stage.getNode().getPointerPosition();
      const x = mousePos.x - 190;
      const y = mousePos.y - 40;
      this.writeMessage('x: ' + x + ', y: ' + y);
    }
  }
};
</script>