JavaScript offers event information of when the user interacts with the screen. What you can do is add an event listener on the <img>
tag holding the picture like so:
document.getElementById("myImg").addEventListener("event type", (event) => {/* consume data */});
Depending on which device you want to work with, you have to set the event accordingly.
If you want to work with mobile device, they make use of Touch events, but if you want to work with laptops you should use Pointer events.
Once you have set your event handlers, you can access the event information in pixels with X and Y = 0px starting in the top left corner, Y growing when going down and X growing when going right. You should pay attention to your device Pixel Ratio because devices can render at a different pixel scale.
Once you handle this, you have to translate the pixels you have into coordinates, which should not be a problem. An easy solution can be to use different formulas after detecting if your event is situated in:
- The top left part
- The top right part
- The bottom left part
- The bottom right part
Example for the top-left part:
const imageSizePx = 1000;
console.log(window.devicePixelRatio);
document.getElementById("myImg").addEventListener("click", (event) => {
// We are in the top left part
if (event.clientX < imageSizePx / 2 && event.clientY < imageSizePx / 2) {
const rect = event.target.getBoundingClientRect();
const x = event.clientX - rect.left; // x position within the element.
const y = event.clientY - rect.top; // y position within the element.
console.log("X = ", getXTopLeft(x));
console.log("Y = ", getYTopLeft(y));
}
});
function getXTopLeft(pixels) {
return -3.5 * (1 - pixels / (imageSizePx / 2));
}
function getYTopLeft(pixels) {
return 3.5 * (1 - pixels / (imageSizePx / 2));
}
<!DOCTYPE html>
<html>
<body style="margin: 0; padding: 0;">
<img
id="myImg"
src="https://i.stack.imgur.com/dS7pa.png"
width="1000"
height="1000"
/>
</body>
</html>