简体   繁体   English

如何获得图像点击时的相对鼠标位置(Vue 3)

[英]How can I get the relative mouse position on image click (Vue 3)

I'm working on trying to get the relative click coordinates on an image.我正在尝试获取图像上的相对点击坐标。 For example, if I click at the very top left of an image, I'm looking to get (0, 0), and for the bottom right, (1, 1) or similar regardless of where on the page the image is.例如,如果我单击图像的最左上角,我希望得到 (0, 0),而对于右下角,(1, 1) 或类似的,无论图像在页面上的位置如何。

This is what I'm trying so far:到目前为止,这是我正在尝试的:

<template>
  <q-page class="flex flex-center">
    <img
      alt="Quasar logo"
      src="~assets/quasar-logo-vertical.svg"
      style="width: 200px; height: 200px"
      @click="onimgClick"
    />
  </q-page>
</template>

<script>
import { defineComponent } from "vue";

export default defineComponent({
  name: "IndexPage",
  methods: {
    onimgClick(event) {
      console.log(event);
    },
  },
});
</script>

This shows a click event in the console as expected, but I don't see an easy way of getting the coordinates relative to the image.这在控制台中显示了预期的点击事件,但我没有看到获取相对于图像的坐标的简单方法。 This is what is printed to console:这是打印到控制台的内容:

_vts: 1671234852933
altKey: false
bubbles: true
button: 0
buttons: 0
cancelBubble: false
cancelable: true
clientX: 635
clientY: 216
composed: true
ctrlKey: false
currentTarget: null
defaultPrevented: false
detail: 1
eventPhase: 0
explicitOriginalTarget: <img alt="Quasar logo" src="/src/assets/quasar-logo-vertical.svg" style="width: 200px; height: 200px;">
isTrusted: true
layerX: 635
layerY: 166
metaKey: false
movementX: 0
movementY: 0
mozInputSource: 1
mozPressure: 0
offsetX: 0
offsetY: 0
originalTarget: <img alt="Quasar logo" src="/src/assets/quasar-logo-vertical.svg" style="width: 200px; height: 200px;">
pageX: 635
pageY: 216
rangeOffset: 0
rangeParent: null
relatedTarget: null
returnValue: true
screenX: 635
screenY: 329
shiftKey: false
srcElement: <img alt="Quasar logo" src="/src/assets/quasar-logo-vertical.svg" style="width: 200px; height: 200px;">​
target: <img alt="Quasar logo" src="/src/assets/quasar-logo-vertical.svg" style="width: 200px; height: 200px;">
timeStamp: 13808
type: "click"
view: Window http://localhost:9000/#/
which: 1
x: 635
y: 216 

I was hoping that offsetX and offsetY would help here, but they appear to always be 0. How can I do this in Vue without having to figure out the bounds of the image on the page and then finding the offset manually?我希望offsetXoffsetY在这里有所帮助,但它们似乎始终为 0。我如何在 Vue 中执行此操作而不必弄清楚页面上图像的边界然后手动查找偏移量?

You could subtract the current mouse position minus the x and y position of your image.您可以减去当前鼠标位置减去图像的 x 和 y 位置。 Something like:就像是:

Check this example检查这个例子

onimgClick(event) { const target = event.target; const bounds = target.getBoundingClientRect(); const posX = event.clientX - bounds.x; const posY = event.clientY - bounds.y; console.log(posX, posY); },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM