Question

[Solved] 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 🙂

Solution #1:

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>
Respondent: sdespont

Solution #2:

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.
});
Respondent: lhoworko

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy