使用鼠标在图片上拖拽矩形框vue

发布时间 2023-03-22 21:17:14作者: 鲤斌
<template>
  <div>
    <img
      class="no-drag"
      src="https://dashanbook.oss-cn-shenzhen.aliyuncs.com/11.png"
      @mousedown="startSelection"
      @mousemove="updateSelection"
      @mouseup="endSelection"
    />
    <div
      v-if="showHighlightBox"
      class="highlight-box"
      :style="{
        width: selectionWidth + 'px',
        height: selectionHeight + 'px',
        left: selectionLeft + 'px',
        top: selectionTop + 'px',
      }"
    ></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      mouseX: 0,
      mouseY: 0,
      selectionStartX: 0,
      selectionStartY: 0,
      selectionEndX: 0,
      selectionEndY: 0,
      showHighlightBox: false,
    };
  },
  methods: {
    startSelection(event) {
      this.selectionStartX = event.pageX;
      this.selectionStartY = event.pageY;
      console.log("startSelection============================");
      this.showHighlightBox = true;
    },
    updateSelection(event) {
      this.mouseX = event.pageX;
      this.mouseY = event.pageY;
      this.selectionEndX = this.mouseX;
      this.selectionEndY = this.mouseY;
      console.log("updateSelection++++++++++++++++++++++++++");
    },
    endSelection() {
      console.log("endSelection-------------------------");
      this.showHighlightBox = false;
      // calculate dimensions of highlight box and determine selected objects
    },
  },
  computed: {
    selectionWidth() {
      return Math.abs(this.selectionEndX - this.selectionStartX);
    },
    selectionHeight() {
      return Math.abs(this.selectionEndY - this.selectionStartY);
    },
    selectionLeft() {
      return Math.min(this.selectionStartX, this.selectionEndX);
    },
    selectionTop() {
      return Math.min(this.selectionStartY, this.selectionEndY);
    },
  },
};
</script>

<style>
.highlight-box {
  position: absolute;
  border: 1px dashed black;
  pointer-events: none;
}
.no-drag {
  -webkit-user-drag: none;
}
</style>