To get the coordinates of a click within an image in HTML using JavaScript, you can use the click event and retrieve the coordinates using event.clientX, event.clientY, event.offsetX, and event.offsetY.
Here’s an example:
Example Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Image Coordinates</title>
</head>
<body>
<h2>Click on the image to get coordinates</h2>
<img id="myImage" src="your-image.jpg" alt="Sample Image" width="500" style="cursor: crosshair;">
<p id="coordinates">Click on the image to see the coordinates.</p>
<script>
document.getElementById("myImage").addEventListener("click", function(event) {
let x = event.offsetX; // X coordinate relative to the image
let y = event.offsetY; // Y coordinate relative to the image
document.getElementById("coordinates").innerText = `X: ${x}, Y: ${y}`;
});
</script>
</body>
</html>
Explanation:
-
event.offsetXandevent.offsetYgive the coordinates relative to the image. -
event.clientXandevent.clientYgive the coordinates relative to the browser window. -
The image has an
id="myImage", and we attach aclickevent listener to it. -
When the image is clicked, the coordinates are displayed in the
<p>element.
Let me know if you need further customizations!
