edisoni.1337 edisoni.1337 - 2 months ago 6
Javascript Question

requestAnimationFrame when using mouse cordinates to make animation

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";
canvas.style.cursor = "auto";

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);


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