0

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>
  • Possible duplicate of [Javascript - Track mouse position](https://stackoverflow.com/questions/7790725/javascript-track-mouse-position) – Sinto Mar 22 '18 at 05:21

1 Answers1

0

You can use the code as:

(function() {
  var canvas = document.getElementById('canvas');
  canvas.onmousemove = handleMouseMove;
  // document.onmousemove = handleMouseMove;
  function handleMouseMove(event) {
    var dot, eventDoc, doc, body, pageX, pageY;

    event = event || window.event; // IE-ism

    // If pageX/Y aren't available and clientX/Y are,
    // calculate pageX/Y - logic taken from jQuery.
    // (This is to support old IE)
    if (event.pageX == null && event.clientX != null) {
      eventDoc = (event.target && event.target.ownerDocument) || document;
      doc = eventDoc.documentElement;
      body = eventDoc.body;

      event.pageX = event.clientX +
        (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
        (doc && doc.clientLeft || body && body.clientLeft || 0);
      event.pageY = event.clientY +
        (doc && doc.scrollTop || body && body.scrollTop || 0) -
        (doc && doc.clientTop || body && body.clientTop || 0);
    }

    // Use event.pageX / event.pageY here
    var coords = "X coords:" + event.pageX + ", Y coords: " + event.pageY;
    document.getElementById("coords").innerHTML = coords;
  }
})();
.rectangle {
  border: 1px solid #FF0000;
  position: absolute;
  left: 100px;
  top: 100px;
  width: 100px;
  height: 200px;
}
<div id="coords"></div>
<div id="canvas">
  <img id="img" src="img.jpg" />
  <div class="rectangle" id="rectangle"></div>
</div>

Thanks to @T.J. Crowder

Sinto
  • 3,915
  • 11
  • 36
  • 70