Vue实现图片框选功能CanvasDemo.vue

Vue中实现图片框选功能,提供了完整的代码参考,您可以将 .vue 文件直接放入项目中查看效果。此功能允许用户在图片上框选区域,后续可以根据需求自主进行修改或新增功能。代码示例如下:



[removed]
export default {
  data() {
    return {
      imageSrc: 'your-image-url.jpg',
      isSelecting: false,
      startX: 0,
      startY: 0,
      endX: 0,
      endY: 0,
    };
  },
  methods: {
    startSelection(event) {
      this.isSelecting = true;
      this.startX = event.offsetX;
      this.startY = event.offsetY;
    },
    drawSelection(event) {
      if (this.isSelecting) {
        this.endX = event.offsetX;
        this.endY = event.offsetY;
        this.drawCanvas();
      }
    },
    endSelection() {
      this.isSelecting = false;
    },
    drawCanvas() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.strokeStyle = 'red';
      ctx.lineWidth = 2;
      ctx.strokeRect(this.startX, this.startY, this.endX - this.startX, this.endY - this.startY);
    },
  },
  mounted() {
    const canvas = this.$refs.canvas;
    canvas.width = this.$refs.image.width;
    canvas.height = this.$refs.image.height;
  },
};
[removed]

<style scoped="">
.canvas-wrapper {
  position: relative;
  display: inline-block;
}
canvas {
  position: absolute;
  top: 0;
  left: 0;
}
</style>

通过此代码,您可以实现简单的图片框选功能,可以根据实际需求进一步自定义与扩展。

vue 文件大小:10.32KB