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!
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
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.
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