我收到错误 Uncaught TypeError: Cannot read property 'getContext' of null
并且文件中的重要部分是......我想知道因为 game.js 在下面的目录中,它不能找到 Canvas ?我该怎么办?
./index.html:
<canvas id="canvas" width="640" height="480"></canvas>
./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);
}
}
}
}
}
最佳答案
我想问题是你的 js 在加载 html 之前运行。
如果您使用的是 jquery,您可以使用文档就绪函数来包装您的代码:
$(function() {
var Grid = function(width, height) {
// codes...
}
});
或者干脆把你的js放在<canvas>
之后.
关于javascript - 无法使用 Canvas 读取 null 的属性 'getContext',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291693/