Reputation: 4240
I would like to be able to get the position of a click in an image. I would like to get the coordinates on the image itself and not in the container of the page.
The closest I have arrived is this:
<template>
<div class="image-annotation">
<div style="position: relative">
<!-- image-annotation__marker class has styles to center place the pointer in a absolute positioning -->
<div class="image-annotation__marker" :style="markerStyle" />
<img
ref="image"
src="https://lh6.ggpht.com/HlgucZ0ylJAfZgusynnUwxNIgIp5htNhShF559x3dRXiuy_UdP3UQVLYW6c=s1200"
alt="Art image"
@click="onClickImage"
/>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class Counter extends Vue {
public activeCoordinates: { x: number; y: number } | null = null;
public $refs!: {
image: HTMLElement
}
get hideSecondColumn() {
return this.activeCoordinates !== null
}
get markerStyle() {
if (this.activeCoordinates === null) return { display: 'none' }
return {
top: `${this.activeCoordinates.y}px`,
left: `${this.activeCoordinates.x}px`,
}
}
public onClickImage(event: MouseEvent) {
this.activeCoordinates = {
x: event.pageX - this.$refs.image.offsetTop,
y: event.pageY - this.$refs.image.offsetLeft,
}
}
}
</script>
But when click on the image I get the following point in the image (the point is not exactly where I clicked)
I would like to get the point exactly where I clicked on the image
Upvotes: 2
Views: 3298
Reputation: 4240
The answer was a very simple solution. Replace event.pageX - this.$refs.image.offsetTop
to event.offsetX
.
From MDN docs:
The offsetX read-only property of the MouseEvent interface provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
vs
The pageX read-only property of the MouseEvent interface returns the X (horizontal) coordinate (in pixels) at which the mouse was clicked, relative to the left edge of the entire document. This includes any portion of the document not currently visible.
Upvotes: 4