简体   繁体   中英

Uncaught TypeError: Cannot read property 'getContext' of null

This is my HTML code, showing the canvas:

 <canvas id="backgroundCanvas" width="550" height=600"></canvas>
 <canvas id="playerCanvas" width="550" height=600"></canvas
 <canvas id="enemiesCanvas" width="550" height=600"></canvas>

This is where the problem is said to occur:

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

the error occurs on line 34 where it says:

Uncaught TypeError: Cannot read property 'getContext' of null

any help is much appreciated :)

It seems your javascript is running before the HTML has finished loading. If you can use jQuery put the js inside of this;

$( document ).ready(function() {
  // js goes in here.
});

Because you have not closed the canvas mark correctly for 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM