vue点击图片获取图片原像素坐标

发布时间 2023-03-22 21:11:42作者: 鲤斌
<template>
  <div>
    <img ref="image"  width="1500px"    :src="imageUrl" @click="handleClick">
    <div v-if="showCoords">X: {{ x }}, Y: {{ y }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: 'https://dashanbook.oss-cn-shenzhen.aliyuncs.com/11.png',
      showCoords: false,
      x: 0,
      y: 0,
      naturalWidth: 0,
      naturalHeight: 0
    };
  },
  mounted() {
    const image = this.$refs.image;
    image.addEventListener('load', () => {
      this.naturalWidth = image.naturalWidth;
      this.naturalHeight = image.naturalHeight;
    });
  },
  methods: {
    handleClick(event) {
      const image = this.$refs.image;
      const rect = image.getBoundingClientRect();
      const x = (event.clientX - rect.left) * (this.naturalWidth / image.width);
      const y = (event.clientY - rect.top) * (this.naturalHeight / image.height);
      this.x = x;
      this.y = y;
      this.showCoords = true;
    },
  },
};
</script>