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.
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.
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.
Simple answer #1 use offsetX and offsetY offsetX; const y = e. offsetY; });
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);
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 */
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With