使用鼠标坐标制作动画时的requestAnimationFrame

时间:2016-08-06 22:15:52

标签: javascript canvas

将使用requestAnimationFrame(animate)调用的动画函数 但是在animate函数中我调用is_inside并且当发生这种情况时我在is_inside函数中遇到错误,当我想得到wx和wy时:未捕获的TypeError:无法读取未定义的属性'clientX' 知道如何解决这个问题吗?谢谢

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

1 个答案:

答案 0 :(得分:3)

这是因为您无法访问请求的帧回调中的任何事件。您需要在mousemove上存储事件中的鼠标位置,并在animate函数

中使用它
var mousePosition = {x: 0, y: 0};

canvas.addEventListener('mousemove', event => {
    mousePosition.x = event.clientX;
    mousePosition.y = event.clientY;
}, false);

然后代替event.clientXevent.clientY分别使用mousePosition.xmousePosition.y