这是我的HTML代码,显示画布:
<canvas id="backgroundCanvas" width="550" height=600"></canvas>
<canvas id="playerCanvas" width="550" height=600"></canvas
<canvas id="enemiesCanvas" width="550" height=600"></canvas>
这就是问题的发生地点:
game.contextBackground = document.getElementById("backgroundCanvas").getContext("2d"); // line 32
game.contextPlayer = document.getElementById("playerCanvas").getContext("2d"); // line 33
game.contextEnemies = document.getElementById("enemiesCanvas").getContext("2d"); // line 34
错误发生在第34行,其中显示:
未捕获的TypeError:无法读取null的“getContext”属性
非常感谢任何帮助:)
答案 0 :(得分:6)
在HTML加载完成之前,您的javascript似乎正在运行。 如果你可以使用jQuery把js放在里面;
$( document ).ready(function() {
// js goes in here.
});
答案 1 :(得分:3)
因为您尚未正确关闭playerCanvas
<canvas id="backgroundCanvas" width="550" height=600"></canvas>
<canvas id="playerCanvas" width="550" height=600"></canvas>
<canvas id="enemiesCanvas" width="550" height=600"></canvas>