TypeError: undefined is not an object (evaluating 'board')

TypeError: undefined is not an object (evaluating 'board')

我尝试使用 canvas 作为扫雷游戏的可点击面板。我的问题是我可以点击 canvas,但我不想这样做。这是我的代码:

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>

我尝试使用板作为对象。但是我失败了。
感谢您的帮助。

将对 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();    
        }*/
    }
}