Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 723
Aearnus Avatar asked Dec 15 '22 18:12

Aearnus


2 Answers

  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

like image 130
MyBoon Avatar answered Dec 18 '22 11:12

MyBoon


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.

like image 38
Vivix Avatar answered Dec 18 '22 09:12

Vivix