Canvas How to - Display mouse position when mouse move








Question

We would like to know how to display mouse position when mouse move.

Answer


<!--  w  w  w  . j  ava  2 s  .  c om-->

<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
canvas {
  margin-left: 25px;
  border: 1px solid red;
}
</style>
</head>
<body>
  <p>Move the mouse over the canvas (the red box)</p>
  <p>
    You are at this position within the canvas<br /> <span id="posX">X:</span><br />
    <span id="posY">Y:</span><br />
  </p>
  <canvas id="myCanvas" width="300" height="300"></canvas>
  <script>
      var canvas = document.getElementById('myCanvas');
      canvas.addEventListener('mousemove', function(event) {
        var bb=canvas.getBoundingClientRect();
        var mouseX=event.clientX-bb.left;
        var mouseY=event.clientY-bb.top;
        document.getElementById("posX").innerHTML="X: "+mouseX;
        document.getElementById("posY").innerHTML="Y: "+mouseY;
      }, false);
    </script>
</body>
</html>

The code above is rendered as follows: