我想使用普通的 javascript 来实现画布 扫雷游戏。我使用2D数组作为我的网格。对于游戏,我需要检测左右鼠标点击,每个点击都会做不同的事情。我的研究指导我mousedown
,mouseup
,contextmenu
,然而,我的代码似乎不起作用,因为右键单击它会执行右键和左键单击的功能,因为右键单击也会触发mouseup事件。任何人都可以帮我理解如何区分这两者?我遇到了event.which
的示例,其中左键单击为event.which === 0
,右键单击为event.which === 2
,但仅适用于按钮,就我而言了解。
这是代码。
canvas.addEventListener('mouseup', function(evt) {
let x1 = Math.floor(evt.offsetX/(canvas.height/rows));
let y1 = Math.floor(evt.offsetY/(canvas.width/cols));
draw (y1, x1); //this is my drawing functions (draws the numbers, bombs)
}, false);
canvas.addEventListener('contextmenu', function(evt) {
let j = Math.floor(evt.offsetX/(canvas.height/rows));
let i = Math.floor(evt.offsetY/(canvas.width/cols));
ctx.drawImage(flagpic, j*widthCell+5, i*widthCell+2, widthCell-9,
widthCell-5); //draws the flag where right mouse clicked
}, false);
答案 0 :(得分:6)
左键单击使用click
事件:
canvas.addEventListener('click', function(evt) { // No right click
使用contextmenu
进行右键单击:(右键单击键盘上下文菜单,也允许鼠标右键单击)
canvas.addEventListener('contextmenu', function(evt) { // Right click
您还需要拨打evt.preventDefault()
以阻止默认操作。
对于您的上下文,如果您想使用mousedown或mouseup事件,则可以使用event.button
来检测单击的按钮:
canvas.addEventListener('mousedown', function(evt) {
if(evt.button == 0) {
// left click
}
这里是按钮点击值:
left button=0,
middle button=1 (if present),
right button=2
您可以查看以下链接中显示的示例以获取更多详细信息:
<script>
var whichButton = function (e) {
// Handle different event models
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left button clicked.');
break;
case 1:
console.log('Middle button clicked.');
break;
case 2:
console.log('Right button clicked.');
break;
default:
console.log('Unexpected code: ' + btnCode);
}
}
}
</script>
<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">
Click with mouse...
</button>
答案 1 :(得分:1)
尝试这可能对您有用
document.getElementById("mydiv").onmousedown = function(event) {
myfns(event)
};
var myfns = function(e) {
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left');
break;
case 1:
console.log('Middle');
break;
case 2:
console.log('Right');
break;
}
}
}
&#13;
<div id="mydiv">Click with mouse...</div>
&#13;
参考
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button