Uncaught TypeError: Cannot read property 'getContext' of null

Inserted the code on JSHint no error, but the browser gives

Uncaught TypeError: Cannot read property 'getContext' of null at app.js:2

What could be the problem?

1. var canvas = document.getElementById('game');
2. var ctx = canvas.getContext('2d');



var ground = new Image();
ground.src = 'img/ground.png';


var food = new Image();
food.src = 'img/food.png';



var box = 32;

var score = 0;


function drawGame() {
    ctx.drawImage(ground, 0,0);
}

var game = setInterval(drawGame, 100);
Author: aleksandr barakin, 2020-08-06

1 answers

I'm fine, check the canvas ID

var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
console.log(ctx); // CanvasRenderingContext2D { ... }
<canvas id="game" width="300" height="300"></canvas>

If the ID doesn't help, then paste <script> at the end of the document. You run the script before the document is rendered

 1
Author: Aziz Umarov, 2020-08-06 06:05:21