无法使用画布读取 null 的属性“getContext" [英] Cannot read property 'getContext' of null, using canvas
本文介绍了无法使用画布读取 null 的属性“getContext"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到错误 Uncaught TypeError: Cannot read property 'getContext' of null
并且文件中的重要部分是...我想知道因为 game.js 在下面的目录中,它不能找到画布?我该怎么办?
I get the error Uncaught TypeError: Cannot read property 'getContext' of null
and the important parts in files are... I am wondering since game.js is in a directory below, it cannot find canvas? What should I do?
./index.html:
./index.html:
<canvas id="canvas" width="640" height="480"></canvas>
./javascript/game.js:
./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 加载之前运行.
I guess the problem is your js runs before the html is loaded.
如果您使用的是 jquery,您可以使用文档就绪函数来包装您的代码:
If you are using jquery, you can use the document ready function to wrap your code:
$(function() {
var Grid = function(width, height) {
// codes...
}
});
或者干脆把你的js放在之后.
Or simply put your js after the <canvas>
.
这篇关于无法使用画布读取 null 的属性“getContext"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文