캔버스를 지뢰 찾기의 클릭 가능한 보드로 사용하려고합니다. 내 문제는 내가 캔버스 밖으로 클릭 수 있지만 그것을 원하지 않는다는 것입니다.TypeError : undefined가 (보드를 평가하는) 객체가 아닙니다.
var board;
var ctx;
var bombs = [];
var clickedX;
var clickedY;
function initBoard(w, h){
\t board = document.getElementById("board");
\t ctx = board.getContext('2d');
\t drawBoard(w,h);
\t placedBombs();
}
function drawBoard(w,h){ \t
\t board.squareSize = {
\t \t w: board.width/w,
\t \t h: board.height/h
\t };
\t
\t ctx.fillStyle = "#C0C0C0"
\t ctx.fillRect(0, 0, board.width, board.height)
\t board.drawGrid = function() {
\t \t ctx.beginPath();
\t \t for (var i = 0; i <= w; i++) {
\t \t \t ctx.moveTo(i * this.squareSize.w, 0);
\t \t \t ctx.lineTo(i * this.squareSize.w, this.height);
\t \t }
\t \t for (var i = 0; i <= h; i++) {
\t \t \t ctx.moveTo(0, i * this.squareSize.h);
\t \t \t ctx.lineTo(this.width, i * this.squareSize.h);
\t \t }
\t \t ctx.lineWidth = 0.3;
\t \t ctx.stroke();
\t \t ctx.closePath();
\t }
\t
\t board.drawGrid(); \t
}
function placedBombs(){
\t for(var n=0; n<10; n++){
\t \t bombs[n] = ([Math.floor(Math.random() * 10), Math.floor(Math.random() * 10)]);
\t } \t
}
board.onmouseup = function(e){
\t board.squareSize = {
\t \t w: board.width/10,
\t \t h: board.height/10
\t };
\t board.eventToGrid = function (e) { \t \t
\t \t return { \t \t \t
\t \t \t i: parseInt(e.offsetX/this.squareSize.w),
\t \t \t j: parseInt(e.offsetY/this.squareSize.h)
\t \t }; \t \t
\t } \t
\t var pos = board.eventToGrid(e);
\t clickedX = pos.i;
\t clickedY = pos.j;
\t loc = document.getElementById("loc");
\t loc.innerHTML = "Position: " + pos.i + ", " + pos.j;
\t if(check(clickedX, clickedY) == false){
\t \t lose();
\t }
\t /*else{
\t \t clickPass(); \t
\t }*/
}
function check(clickedX, clickedY){
\t console.log(clickedX);
\t console.log(clickedY); \t
\t for(var i=0; i<bombs.length; i++){
\t \t if((clickedX == bombs[i][0]) && (clickedY == bombs[i][1])){
\t \t \t return false;
\t \t }
\t }
\t return true; \t
}
/*function clickPass(){
\t
}*/
\t
function lose(){
\t alert("bomb");
}
<body onload="initBoard(10,10)">
<canvas id="board" width="350" height="350">
</canvas>
<div id="loc">
Mouse location: x, y
</div>
</body>
내가 개체로 보드를 사용하려고 : 여기에 내 코드입니다. 그러나 나는 실패했다.
도움 주셔서 감사합니다.
어디에서 오류가 발생합니까? – Barmar
'board'가 정의되어 있지 않으면, 뭔가가'initBoard'가 실행되는 것을 막을 수 있습니다. – Barmar
죄송합니다, 지금 편집하십시오. board.onmouseup 내가 this.onmouseup 내가 그것을 사방에 클릭했을 때 내 문제입니다. 내가 이런 식으로 사용했을 때'TypeError : undefined가 (보드 '를 평가하는) 객체가 아니다' –