我已经制作了一些类似pacman的形状,这些形状在html5画布上动画显示,当页面上的按钮被点击时,它们当前可以跟随鼠标(鼠标移动的任何地方)。除了跟随光标之外,当按下每个相应的按钮时,对象可以在四个方向上移动(即,向左,向右,向上,向下)。问题是,单击跟随按钮后,即使单击任何其他按钮,对象也将继续跟随光标。我需要一种方法来获得另一个可以点击以中断“跟随”事件的按钮。如果这是不可能的,使用setInterval函数调用来设置follow事件的时间限制可能会有效,但我不知道如何实现它。实现此功能的最佳方法是什么? “跟随”动画的代码如下:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
$("#follow").click(function () {
canvas.addEventListener('mousemove', function (evt) {
//WokkaWokkas is the array of the pacman objects
var mousePos = getMousePos(canvas, evt);
WokkaWokkas[0].posX = mousePos.x - 50;
WokkaWokkas[0].posY = mousePos.y - 50;
WokkaWokkas[1].posX = WokkaWokkas[0].posX - 100;
WokkaWokkas[1].posY = WokkaWokkas[0].posY - 100;
}, false);
});
$("#follow").click(function () {
//not sure if this is the syntax for using (canvas).on
(canvas).on('mousemove', function (evt) {
var mousePos = getMousePos(canvas, evt);
WokkaWokkas[0].posX = mousePos.x - 50;
WokkaWokkas[0].posY = mousePos.y - 50;
WokkaWokkas[1].posX = WokkaWokkas[0].posX - 100;
WokkaWokkas[1].posY = WokkaWokkas[0].posY - 100;
}, false);
});
animationLoop();
$("#up").click(function () {
$(canvas).off('mousemove');
WokkaWokkas[0].direction = up;
});
$("#down").click(function () {
$(canvas).off('mousemove');
WokkaWokkas[0].direction = down;
});
$("#left").click(function () {
$(canvas).off('mousemove');
WokkaWokkas[0].direction = left;
});
$("#right").click(function () {
$(canvas).off('mousemove');
WokkaWokkas[0].direction = right;
});
$("#unfollow").click(function () {
$(canvas).off('mousemove');
WokkaWokkas[0].posX = 25;
WokkaWokkas[0].posY = 25;
});
答案 0 :(得分:1)
你能不能只在按下另一个按钮时删除事件监听器?
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function followMouse(evt) {
//WokkaWokkas is the array of the pacman objects
var mousePos = getMousePos(canvas, evt);
WokkaWokkas[0].posX = mousePos.x - 50;
WokkaWokkas[0].posY = mousePos.y - 50;
WokkaWokkas[1].posX = WokkaWokkas[0].posX - 100;
WokkaWokkas[1].posY = WokkaWokkas[0].posY - 100;
}
$("#follow").click(function () {
canvas.addEventListener('mousemove', followMouse, false);
});
$("#otherBtn").click(function() {
canvas.removeEventListener('mousemove', followMouse);
});
顺便说一下,如果您已经在使用jQuery,为什么不使用他们的事件系统呢?
$(canvas).on('mousemove', function(e) {});
$(canvas).off('mousemove');
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
更新这是因为removeEventListener只删除了一个侦听器,因此您需要引用该函数