Aearnus
Aearnus

Reputation: 541

Getting cursor position in a canvas without jQuery

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!

Upvotes: 4

Views: 5589

Answers (2)

MyBoon
MyBoon

Reputation: 1298

  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

Upvotes: 12

Vivix
Vivix

Reputation: 120

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.

Upvotes: 1

Related Questions