You can’t simply pass a function an arbitrary event
argument. You need to tell javascript that this function listens for a mouse event on the canvas. You do this by adding it as an event listener:
var mousepos;
var canvas = document.getElementById('myCanvas');
function getMousePos(event) {
var rect = canvas.getBoundingClientRect();
var mx = event.clientX - rect.left;
var my = event.clientY - rect.top;
mousepos = {
x: mx,
y: my,
}
console.log(mousepos);
}
canvas.addEventListener("mousemove",getMousePos);
<canvas id = "myCanvas"></canvas>
Whenever the user moves the mouse over the canvas, the mouseOver
event is triggered. Since we have assigned getMousePos
to listen to this event, javascript automatically passes the event
parameter, and we can now read the relevant properties. Whenever the user moves their mouse, we console.log()
the position.
In this line :
var mousePos = getMousePos(event, canvas);
You are passing a variable event
that isn’t defined. As redouglas said, you must pass getMousePos
in an actual mouse event
A correct script would be :
var canvas = document.getElementById('myCanvas');
function getMousePos(event, canvas) {
var rect = canvas.getBoundingClientRect();
var mx = event.clientX - rect.left;
var my = event.clientY - rect.top;
var mousePos = {
x: mx,
y: my,
}
console.log("Mouse position x = " + mousePos.x + " y = " + mousePos.y);
}
canvas.addEventListener("mousemove", function(event) {
var rect = canvas.getBoundingClientRect();
var mx = event.clientX - rect.left;
var my = event.clientY - rect.top;
var mousePos = {
x: mx,
y: my,
}
console.log("Mouse position x = " + mousePos.x + " y = " + mousePos.y);
});
But as it depends on your needs, I suggest you to have a look on the linked MDN ressource.
I’m not sure why I keep getting the error ‘cannot read property of clientX of undefined.
My understanding is that event.clientX should give me the x coordinate and event.clientY the Y coordinate.
Please can you tell me where I’m going wrong?
var canvas = document.getElementById('myCanvas');
function getMousePos(event,canvas) {
var rect = canvas.getBoundingClientRect();
var mx = event.clientX - rect.left;
var my = event.clientY - rect.top;
return { // the getMousePos function returns an object. It’s a factory
x: mx,
y: my,
}
}
var mousePos = getMousePos(event, canvas);
console.log("Mouse position x = " + mousePos.x + " y = " + mousePos.y);
You are not using an Event at all. If you were, that
Thanks that worked, do you know why the return key word didn’t work in my original code? I expect that to give me the coordinates too according to the course I’m doing
It’s because your function required an event argument, but it only gets passed that argument if you have the function inside an event listener. So in your case,