[英]TypeError: undefined is not an object (evaluating 'board')
I try to use canvas as a clickable board for minesweeper. 我尝试将画布用作扫雷器的可点击面板。 My problem is that i can clicked out of the canvas but i don't want to it.
我的问题是我可以从画布上单击一下,但我不想这么做。 Here's my code:
这是我的代码:
var board; var ctx; var bombs = []; var clickedX; var clickedY; function initBoard(w, h){ board = document.getElementById("board"); ctx = board.getContext('2d'); drawBoard(w,h); placedBombs(); } function drawBoard(w,h){ board.squareSize = { w: board.width / w, h: board.height / h }; ctx.fillStyle = "#C0C0C0" ctx.fillRect(0, 0, board.width, board.height) board.drawGrid = function () { ctx.beginPath(); for (var i = 0; i <= w; i++) { ctx.moveTo(i * this.squareSize.w, 0); ctx.lineTo(i * this.squareSize.w, this.height); } for (var i = 0; i <= h; i++) { ctx.moveTo(0, i * this.squareSize.h); ctx.lineTo(this.width, i * this.squareSize.h); } ctx.lineWidth = 0.3; ctx.stroke(); ctx.closePath(); } board.drawGrid(); } function placedBombs(){ for(var n=0; n<10; n++){ bombs[n] = ([Math.floor(Math.random() * 10), Math.floor(Math.random() * 10)]); } } board.onmouseup = function(e){ board.squareSize = { w: board.width / 10, h: board.height / 10 }; board.eventToGrid = function (e) { return { i: parseInt(e.offsetX / this.squareSize.w), j: parseInt(e.offsetY / this.squareSize.h) }; } var pos = board.eventToGrid(e); clickedX = pos.i; clickedY = pos.j; loc = document.getElementById("loc"); loc.innerHTML = "Position: " + pos.i + ", " + pos.j; if(check(clickedX, clickedY) == false){ lose(); } /*else{ clickPass(); }*/ } function check(clickedX, clickedY){ console.log(clickedX); console.log(clickedY); for(var i=0; i<bombs.length; i++){ if((clickedX == bombs[i][0]) && (clickedY == bombs[i][1])){ return false; } } return true; } /*function clickPass(){ }*/ function lose(){ alert("bomb"); }
<body onload="initBoard(10,10)"> <canvas id="board" width="350" height="350"> </canvas> <div id="loc"> Mouse location: x, y </div> </body>
I try to use board as an object. 我尝试使用木板作为对象。 But i failed.
但是我失败了。
Thanks for your helps. 感谢您的帮助。
Put the assignment to board.onmouseup
inside initBoard()
, so that it runs after you've assigned the variable. 把分配给
board.onmouseup
内initBoard()
所以它运行您指定的变量之后。
function initBoard(w, h){
board = document.getElementById("board");
ctx = board.getContext('2d');
drawBoard(w,h);
placedBombs();
board.onmouseup = function(e){
board.squareSize = {
w: board.width / 10,
h: board.height / 10
};
board.eventToGrid = function (e) {
return {
i: parseInt(e.offsetX / this.squareSize.w),
j: parseInt(e.offsetY / this.squareSize.h)
};
}
var pos = board.eventToGrid(e);
clickedX = pos.i;
clickedY = pos.j;
loc = document.getElementById("loc");
loc.innerHTML = "Position: " + pos.i + ", " + pos.j;
if(check(clickedX, clickedY) == false){
lose();
}
/*else{
clickPass();
}*/
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.