首先,我捕获鼠标事件如下:
window.addEventListener("mousemove", main.mouseEvent, false);
window.addEventListener("mouseup", main.mouseEvent, false);
window.addEventListener("mousedown", main.mouseEvent, false);
然后使用右键单击禁用
contextmenu
:
window.addEventListener('contextmenu', function (e) {
// do something here...
e.preventDefault();
}, false);
然后在游戏深处的某个地方,会触发地图的
mousePressed
、mouseReleased
和mouseMoved
事件,即:
mousePressed(x, y, event) {
let result = false;
if (event.button === 2) {
this.isMousePressed = true;
this.mousePressedPos.x = x;
this.mousePressedPos.y = y;
result = true;
}
return result;
}
mouseReleased(x, y, event) {
if (event.button === 2) {
this.isMousePressed = false;
return true;
}
return false;
}
mouseMoved(x, y, event) {
let result = false;
this.mousePos.x = x;
this.mousePos.y = y;
if (this.isMousePressed) {
// move map with mouse
let dx = x - this.mousePressedPos.x;
let dy = y - this.mousePressedPos.y;
this.setPosition(this.x + dx, this.y + dy);
this.mousePressedPos.x = x;
this.mousePressedPos.y = y;
result = true;
}
return result;
}
上面的代码部分应该允许用户使用鼠标右键拖动地图。当使用
button===0
或 button===1
时,代码适用于左键单击和中键单击。当使用 right 时,它会移动一小部分(可能是几个像素)并继续停止工作。我在另一款与我正在制作的游戏类似的游戏中注意到了这一点。 Firefox 和 Edge 都会出现问题。
关于造成此问题的原因以及如何解决它有什么建议吗?
编辑
按照要求,
main.mouseEvent
。不确定这有什么帮助?
function mouseEvent(event) {
let rect = main._gameCanvas.getBoundingClientRect();
let pos = {
x: event.clientX - rect.left,
y: event.clientY - rect.top
}
main.game.mouseEvent(pos.x, pos.y, event);
}
这是一个非常简单的过程:
main.mouseEvent
-> gameLayer.mouseEvent
-> layer.mouseEvent
-> 切换事件类型 -> 传递到相应的函数(mouseMoved
, mousePressed
, mouseReleased
)。
问题是,我知道它在使用
button===0
和 button===1
时有效,所以这个问题实际上并不与我的代码有关。这要么是浏览器问题,要么是我不知道的属性/设置,我需要在某个地方进行更改。
编辑2
为了更加清晰起见,这个游戏过去使用右键拖动地图。现在它出现了与我的代码中相同的问题,这表明我的代码中没有出现问题(例如更新浏览器如何处理上下文菜单或类似内容)