未定义html5 canvas obj.addEventListener

时间:2017-07-15 01:45:34

标签: javascript html5 canvas

我正在尝试单击画布并获取鼠标位置,类似于Getting mouse location in canvas

var board = new function(){
    this.id = document.getElementById("board");
    this.ctx = this.id.getContext("2d");
}

function newGame(piece) {
    drawGrid();
    board.addEventListener("click", getMousePosition);
    if (piece == "X") {
        players.player = "X";
        players.computer = "O";
    } else {
        players.player = "O";
        players.computer = "X";
    }
}

我一直在绞尽脑汁和互联网试图解决这个问题。有Cannot attach Event listener to canvas?,但我没有使用getElementsByTagName。我看了MouseMove issue on canvas,但我的画布不应该像我定义的那样超出范围。 event listener on canvas in html5 issue没有帮助,因为我没有尝试向上下文添加侦听器。有人可以告诉我发生了什么事吗?

https://codepen.io/csinclair/pen/owVqyq

1 个答案:

答案 0 :(得分:0)

元素是board.id,而不是board。

应该是     board.id.addEventListener("click", getMousePosition);