How to get the correct html5 canvas x y coordinates?

0 votes
124 views
asked Feb 3, 2014 in HTML5 by admin (8,115 points)

HI all

How to get the correct html5 canvas x y coordinates?

1 Answer

0 votes
answered Feb 3, 2014 by harish
function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
 
      canvas.addEventListener('mousemove', function(evt) {
        var mousePos = getMousePos(canvas, evt);
        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
      }, false);
...