我正在尝试通过使用画布创建Minesweeper游戏的指南来学习Javascript。除了我点击选项栏之外,它将其注册为画布上的点击。This is a screenshot of the whole game so far.我仍然可以点击画布,它可以正常工作,这一切都很顺利。但是点击选项栏(带有笑脸的部分),它也会在画布上单击注册,并删除其中一个图块。
以下是注册鼠标点击的代码:
'
if(e.offsetX) { //Get's mouse pos relative to the canvas pos
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
//mouseX = e.pageX; //Gets mouse pos relatiove to page
//mouseY = e.pageY;
//console.log("Mouse Pos on screen (x, y) = " + mouseX + "," + mouseY);//Validate that the mouse position is being recorded.
//Algorithm to tell which cube the click was on.
if (Math.floor(mouseX/settings.width) < settings.columns && Math.floor(mouseY/settings.height) < settings.rows){
clickX = Math.floor(mouseX/settings.width);
clickY = Math.floor(mouseY/settings.height);
console.log("Coords of clicked box (x,y)" + clickX + "," + clickY);
}
`
希望这足以让某人发现问题,因为我无法做到。
答案 0 :(得分:0)
我认为问题在于您在一个功能中捕获整个窗口的点击事件,因此无论您是在画布上还是在新的游戏div上,还是在窗口的其他位置,您和#39;尝试将该点击应用到画布上。建议您最好为画布本身进行点击事件,并为新游戏设置另一个点击事件(这应该是一个按钮,而不是div,但我离题了)
如果真的希望继续这种方式,您可以明确地将您的功能限制为仅关注您的画布。如果你使gCanvas全局(颤抖)
var gCanvas = null;
function canvasLoad() {
gCanvas = document.getElementById("gameCanvas");
...
}
然后在您的事件函数中,您可以检查事件的目标,并且只对从画布触发的事物执行操作
window.onclick = function(e){
...
//Algorithm to tell which cube the click was on.
if (
(e.target === gCanvas )
)
{
if (Math.floor(mouseX/settings.width) < settings.columns &&
Math.floor(mouseY/settings.height) < settings.rows)
{
clickX = Math.floor(mouseX/settings.width);
clickY = Math.floor(mouseY/settings.height);
console.log("Coords of clicked box (x,y)" + clickX + "," + clickY);
}
}
请注意,此并非我所采用的解决方案。事件与触发它的对象的紧密绑定更令人满意。
<canvas id = "gameCanvas" width="153" height="153"
style="border:1px solid #000000;" #
onclick='return myCanvasEventHandler()'></canvas>
这将明确限制myCanvasEventHandler()函数仅触发画布本身的事件。