Solve - Cannot read property 'getContext' of Null in JS

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Bob Orchard

Solve - Cannot read property 'getContext' of Null #

The "Cannot read property 'getContext' of null" error occurs for 2 reasons:

  1. Calling the getContext method on a non-existent canvas element.
  2. Inserting the JS script tag above the HTML, where the canvas element is declared.
index.js
const canvas = document.getElementById('does-not-exist'); console.log(canvas); // ๐Ÿ‘‰๏ธ null // โ›”๏ธ Cannot read properties of null (reading 'getContext') const ctx = canvas.getContext('2d');

To solve the "Cannot read property 'getContext' of null" error, make sure you're providing the correct id when trying to get the canvas element. The error often occurs when providing an invalid id to the getElementById method.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โœ… id should match your JS code --> <canvas id="canvas" width="500" height="500"></canvas> <script src="index.js"></script> </body> </html>

To solve the "Cannot read property 'getContext' of null" error, place the JS script tag at the bottom of the body, after the canvas element has been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โŒ BAD - script is ran before canvas is created โŒ --> <script src="index.js"></script> <canvas id="canvas" width="500" height="500"></canvas> </body> </html>

The index.js script is executed before the canvas element is created, therefore you can't access the element inside the index.js file.

index.js
const canvas = document.getElementById('canvas'); console.log(canvas); // ๐Ÿ‘‰๏ธ null // โ›”๏ธ Cannot read properties of null (reading 'getContext') const ctx = canvas.getContext('2d');

You should place the JS script tag at the bottom of the body, after the DOM elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> <!-- โœ… GOOD - canvas is already created โœ… --> <script src="index.js"></script> </body> </html>

Now you can access the canvas element inside of the index.js file.

index.js
const canvas = document.getElementById('canvas'); console.log(canvas); // ๐Ÿ‘‰๏ธ canvas#canvas // โœ… works const ctx = canvas.getContext('2d'); console.log(ctx); // ๐Ÿ‘‰๏ธ CanvasRenderingContext2D

Conclusion #

The "Cannot read property 'getContext' of null" error occurs when calling the getContext method on a null value.

To solve the error, make sure the JS script tag is loaded after the HTML is declared and the id of the element exists in the DOM.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee