Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting mouse location in canvas [duplicate]

Is there a way to get the location mouse inside a <canvas> tag? I want the location relative to to the upper right corner of the <canvas>, not the entire page.

like image 541
Sam Lee Avatar asked Jul 11 '09 19:07

Sam Lee


People also ask

How do you get the mouse position on canvas?

To get real mouse position in canvas with JavaScript, we use the canvas getBoundingClientRect method. const getMousePos = (canvas, evt) => { const rect = canvas. getBoundingClientRect(); return { x: ((evt.

Does canvas detect mouse movement?

Rumors circulated earlier this semester among students about a new function on Canvas that professors can use to monitor students' mouse movements and the new tabs they opened. But these rumors are false, said Mario Guerra, UT Canvas service manager.

Which method is used to get the Y coordinate of the point where user have clicked using mouse button?

Simple answer #1 use offsetX and offsetY offsetX; const y = e. offsetY; });


3 Answers

The accepted answer will not work every time. If you don't use relative position the attributes offsetX and offsetY can be misleading.

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);
like image 197
AxFab Avatar answered Oct 22 '22 18:10

AxFab


Easiest way is probably to add a onmousemove event listener to the canvas element, and then you can get the coordinates relative to the canvas from the event itself.

This is trivial to accomplish if you only need to support specific browsers, but there are differences between f.ex. Opera and Firefox.

Something like this should work for those two:

function mouseMove(e)
{
    var mouseX, mouseY;

    if(e.offsetX) {
        mouseX = e.offsetX;
        mouseY = e.offsetY;
    }
    else if(e.layerX) {
        mouseX = e.layerX;
        mouseY = e.layerY;
    }

    /* do something with mouseX/mouseY */
}
like image 44
Jani Hartikainen Avatar answered Oct 22 '22 19:10

Jani Hartikainen


Also note that you'll need CSS:

position: relative;

set to your canvas tag, in order to get the relative mouse position inside the canvas.

And the offset changes if there's a border

like image 23
Nat Avatar answered Oct 22 '22 18:10

Nat