使用canvas无法读取null的属性'getContext'

Kob*_*obi 37 html javascript canvas

我得到错误Uncaught TypeError: Cannot read property 'getContext' of null和文件中的重要部分是......我想知道因为game.js在下面的目录中,它找不到画布?我该怎么办?

./index.html:

<canvas id="canvas" width="640" height="480"></canvas>
Run Code Online (Sandbox Code Playgroud)

./javascript/game.js:

var Grid = function(width, height) {
        ...
        this.draw = function() {
        var canvas = document.getElementById("canvas");
        if(canvas.getContext) {
            var context = canvas.getContext("2d");
            for(var i = 0; i < width; i++) {
                for(var j = 0; j < height; j++) {
                    if(isLive(i, j)) {
                        context.fillStyle = "lightblue";
                    }
                    else {
                        context.fillStyle = "yellowgreen";
                    }
                    context.fillRect(i*15, j*15, 14, 14);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

C. *_*ung 70

我想问题是你的js在加载html之前运行.

如果您使用的是jquery,则可以使用文档就绪函数来包装代码:

$(function() {
    var Grid = function(width, height) {
        // codes...
    }
});
Run Code Online (Sandbox Code Playgroud)

或者简单地把你的js放在后面<canvas>.

  • 在[此处](http://jquery.com/)下载jquery,然后将其添加到您的文件中&lt;script type =“ text / javascript” src =“ jquery-1.7.2.min.js”&gt; &lt;/ script&gt; `。将您的代码放入$(function(){});中,就像我在答案中写的一样。 (3认同)

Crs*_*ero 12

将JavaScript放在标记之后 <canvas></canvas>


Pet*_*ter 9

您不必包含JQuery.

在index.html:
<canvas id="canvas" width="640" height="480"></canvas><script src="javascript/game.js"> 这应该没有JQuery ...

编辑:你应该把脚本标签放在body标签中......