Last updated: Mar 3, 2024
Reading timeยท2 min
The "Cannot read properties of null (reading 'getContext')" error occurs for 2 reasons:
getContext
method on a non-existent canvas
element.Here is an example of how the error occurs.
const canvas = document.getElementById('does-not-exist'); console.log(canvas); // ๐๏ธ null // โ๏ธ Uncaught TypeError: Cannot read properties of null (reading 'getContext') const ctx = canvas.getContext('2d');
We attempted to call the getContext()
method on a null
value which caused
the error.
getContext()
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.
<!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>
The id
in your HTML code should be the same as the id
you pass in the call
to the document.getElementById()
method.
Place the JS script tag at the bottom of the body tag, after the canvas element has been created.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โ BAD - script is run before canvas is created โ --> <script src="index.js"></script> <canvas id="canvas" width="500" height="500"></canvas> </body> </html>
The index.js
script is run before the canvas
element is created, so you
can't access the element inside the index.js
file.
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.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> <h2>bobbyhadz.com</h2> <!-- โ 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.
const canvas = document.getElementById('canvas'); console.log(canvas); // ๐๏ธ canvas#canvas // โ works const ctx = canvas.getContext('2d'); console.log(ctx); // ๐๏ธ CanvasRenderingContext2D
HTML code is parsed from top to bottom, so the script tag has to be placed at the bottom of the body tag, after all of the DOM elements it needs to access.
The "Cannot read properties of null (reading 'getContext')" 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.