nka*_*yan 2 javascript html5 canvas mouseevent mouseup
我想用普通的javascript实现一个帆布 扫雷游戏.我使用2D数组作为我的网格.对于游戏,我需要检测左右鼠标点击,每个点击都会做不同的事情.我的研究直接对我,,,但是,我的代码似乎没有工作,作为右键点击它的功能右和左击,因为鼠标松开事件被触发右键为好.任何人都可以帮我理解如何区分这两者?我遇到了左键单击的示例,右键单击,但这仅适用于按钮,据我所知.这是代码.mousedownmouseupcontextmenuevent.whichevent.which === 0event.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);
Run Code Online (Sandbox Code Playgroud)
使用click事件进行左键单击:
canvas.addEventListener('click', function(evt) { // No right click
Run Code Online (Sandbox Code Playgroud)
并contextmenu用于右键单击:(右键单击键盘上下文菜单,也允许鼠标右键单击)
canvas.addEventListener('contextmenu', function(evt) { // Right click
Run Code Online (Sandbox Code Playgroud)
您还需要调用evt.preventDefault()以防止默认操作.
对于您的上下文,如果您想使用mousedown或mouseup事件,则可以使用event.button以检测单击的按钮:
canvas.addEventListener('mousedown', function(evt) {
if(evt.button == 0) {
// left click
}
Run Code Online (Sandbox Code Playgroud)
这是按钮点击值:
left button=0,
middle button=1 (if present),
right button=2
Run Code Online (Sandbox Code Playgroud)
您可以查看以下链接中显示的示例以获取更多详细信息:
<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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4360 次 |
| 最近记录: |