4

I am trying to learn how to use the HTML canvas element, and naturally, I am making a drawing application. So, I have the code set up for the actual drawing and animating part of the app, but I am not sure how to approach getting the position of the mouse cursor.

I really would prefer not to use jQuery, for I would rather not want to learn all of what it does and have to go through the process of getting it set up. Thanks for any help!

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Aearnus
  • 541
  • 6
  • 21

2 Answers2

12
  function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect(), root = document.documentElement;

    // return relative mouse position
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return {
      x: mouseX,
      y: mouseY
    };
  }

  window.onload = function() {
    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;
      alert(message);
    }, false);
  };

Source

Teddy Garland
  • 117
  • 2
  • 7
MyBoon
  • 1,290
  • 1
  • 10
  • 18
  • 1
    This is the only solution I've seen that uses `document.documentElement` -- in what situation is it necessary to subtract root? – P i Apr 15 '15 at 14:10
  • That makes sense, in order to get an relative position within the canvas. For example: Page is scrolled down 200px. Canvas is mounted at 20px, 400px (x,y). Event fires. `clientX` and `clientY` return a position within the viewport of `(40px, 300px)`. The simple math above would tell you that this is `(20px, 100px)` within the canvas. – STRML Apr 15 '15 at 14:11
1

When using it to draw on a canvas, I prefer this code:

    function getMousePos(canvas, event)
{
    var mouseX = event.pageX - canvas.offsetLeft;
    var mouseY = event.pageY - canvas.offsetTop;
    return {
        x: mouseX,
        y: mouseY };
}

This was the code that I used to avoid scrolling, position and other issues I got with getting the correct position of the mouse.

Vivix
  • 120
  • 6