I want to get the mouse coordinates relative to img
, but when the mouse is on the rectangle
, it returns the coordinates relative to it.
How do I get the coordinates properly?
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<style>
.rectangle {
border: 1px solid #FF0000;
position: absolute;
left:100px;
top:100px;
width:100px;
height:200px;
}
</style>
<title></title>
</head>
<body>
<div id="coords"></div>
<div id="canvas">
<img id="img" src="img.jpg" />
<div class="rectangle" id="rectangle"></div>
</div>
<script>
var canvas = document.getElementById('canvas');
canvas.onmousemove = function (event) {
var x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("img").offsetLeft;
var y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("img").offsetTop;
console.log(event.target.id)
var coords = "X coords:" + x + ", Y coords: " + y;
document.getElementById("coords").innerHTML = coords;
}
</script>
</body>
</html>