I have an HTML image that I want to pan & zoom programatically. In order to improve the experience, I added a CSS transition for smoothness.
When I click on the image, I need to determine the mouse position within the image. Currently, event.offsetX
gives me the mouse position within the image at the current frame of the animation.
I would like to know the mouse position as if the animation finished already (even though it hadn’t).
Here is another way of explaining the problem. I created below an example where an image zooms in after we click on the button. The zoom takes 5 seconds. During the zoom, if I keep my mouse fixed and keep clicking, the offset value changes as the image moves on the screen and then it stabilizes after 5 seconds and returns the same offset value. I would like to know that final offset value before the animation finishes if possible.
<button onclick="onButton()">Zoom</button>
<br>
<img
id='img'
onclick="onImage(event)"
src="https://picsum.photos/id/237/200"
style="transition: 5s ease"
>
<script>
function onButton() {
const img = document.querySelector('#img')
img.style.scale = 5.0
}
function onImage(event) {
console.log(event.offsetX, event.offsetY)
}
</script>
2
Answers
In the provided code snippet, the onButton() function is triggered when the "Zoom" button is clicked, and it attempts to scale up the image by setting the scale style property. However, the correct property to use for scaling is transform: scale(). Additionally, the onImage(event) function logs the event.offsetX and event.offsetY values when the image is clicked.
To modify the code to achieve the desired zoom effect and obtain accurate coordinates, you can make the following adjustments:
If you don’t mind adding some additional HTML and CSS:
This work by zooming an invisible div behind the image without transition, and transfer the click event to that div instead of the image itself