未捕获的TypeError:无法读取null的属性'getContext'

use*_*436 0 javascript jquery

这是我的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>
Run Code Online (Sandbox Code Playgroud)

这就是据说发生问题的地方:

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
Run Code Online (Sandbox Code Playgroud)

错误发生在第34行,它说:

未捕获的TypeError:无法读取null的属性'getContext'

任何帮助深表感谢 :)

lho*_*rko 6

在HTML加载完成之前,您的javascript似乎正在运行.如果你可以使用jQuery把js放在里面;

$( document ).ready(function() {
  // js goes in here.
});
Run Code Online (Sandbox Code Playgroud)