Reputation: 4433
animation function that will be called using requestAnimationFrame(animate) but in the animate function i call is_inside and when that happends i get an error in is_inside function when i want to get wx and wy : Uncaught TypeError: Cannot read property 'clientX' of undefined Any idea how to fix this ? Thank you
function animate(event){
targetX = event.clientX - canvas.getBoundingClientRect().left;
targetY = event.clientY - canvas.getBoundingClientRect().top;
canvas.style.cursor = "pointer";
if(clicked!=true){
if(is_inside(pointx,pointy)){
move();
}else{
canvas.style.cursor = "auto";
moveLeft();
}
}
}
function is_inside(x,y){
var wx = event.clientX - canvas.getBoundingClientRect().left;
var wy = event.clientY - canvas.getBoundingClientRect().top;
var distance = Math.sqrt((wx-x-400)*(wx-x-400) + (wy-y-300)*(wy-y-300));
if(distance < 35){
return true;
}else {
return false;
}
}
canvas.addEventListener('mousemove', animate, false);
Upvotes: 2
Views: 2435
Reputation: 5343
This is because you won't have access to any event in requested frame callback. You need to store mouse position from event on mousemove and just use it in animate
function
var mousePosition = {x: 0, y: 0};
canvas.addEventListener('mousemove', event => {
mousePosition.x = event.clientX;
mousePosition.y = event.clientY;
}, false);
then instead of event.clientX
and event.clientY
use mousePosition.x
and mousePosition.y
respectively
Upvotes: 4