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>.
您不必包含JQuery.
在index.html:
<canvas id="canvas" width="640" height="480"></canvas><script src="javascript/game.js">
这应该没有JQuery ...
编辑:你应该把脚本标签放在body标签中......
| 归档时间: |
|
| 查看次数: |
132356 次 |
| 最近记录: |