getting mouse position with javascript within canvas

I see plenty of question on this subject and all propose to browse DOM or use offsetX and offsetY, which are not always set right.

You should use the function: canvas.getBoundingClientRect() from the canvas API.

  function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
  }

  canvas.addEventListener('mousemove', function(evt) {
    var mousePos = getMousePos(canvas, evt);
    console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y);
  }, false);

Leave a Comment