TypeError: Cannot read properties of null(reading 'getContext')

There is supposed to be a square moving left, but nothing is showing in my canvas and I’m getting this error: TypeError: Cannot read properties of null (readying ‘getContext’)
My code:

const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
const CANVAS_WIDTH = canvas.width = 600;
const CANVAS_HEIGHT = canvas.height = 600;

const playerImage = new Image();
playerImage.src = 'skull.png';
let x=0;

function animate(){
  ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  ctx.fillRect(x, 50, 100, 100);

Also, the link to the repl is here : https://bruh.catv5.repl.co/__repl

The problem is that the script tag is placed before the canvas tag in the HTML, so when the script runs, the canvas doesn’t exist yet.

You have to move the script tag below the canvas tag.

<canvas id="canvas1"></canvas>
<script src="script.js"></script>

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.