2

I am trying to make the background of the canvas but I can't use getContext. I get the error:

Uncaught TypeError: Cannot read property 'getContext' of null at game.js:4

Html

<!DOCTYPE html>
<html>
    <head>
        <meta charset= "UTF-8">
        <title>Game</title>
    </head>
    <body>
        <script src="game.js"></script>
        <canvas id="canvas" width="100" height="320"></canvas>
    </body>
</html>

Javascript


const canvas = document.getElementById('canvas');
if (canvas != null) {
  ctx = canvas.getContext("2d");
} else {
  console.log('wtf happen');
}


function draw(){
    ctx.background(255,0,0);
}

I have already tried using the post: Cannot read property 'getContext' of null

but it did not help me.

CarmiteStars
  • 25
  • 2
  • 6
  • Where is your JavaScript in relation to the DOM element? My guess is your javascript is running before the DOM element is there. You should put your JS right about the closing

    tag so it runs after all the elements have rendered.

    – pizzarob Jul 11 '19 at 21:23
  • So one thing that could have helped your debugging would be to do `console.log(canvas)`. When getElementById can't find an element, it returns null. In your case, it happened because you called the function before the canvas element was rendered on the DOM. – Ibu Jul 11 '19 at 21:31
  • answered : [he purpose of Typescript is to avoid wrong types. By default document.getElementById returns a HTMLElementtype which is a generic type. In order to make your app understand it is a canvas element you need to cast it using syntax.](https://stackoverflow.com/a/58218739/7943013) – Litaf Kupfer Jun 14 '21 at 13:47

1 Answers1

4

This is because you are calling your javascript before the element is added to the page/DOM and the browser runs/loads code/HTML synchronously (one line at a time).

So, this leaves us with three options:

Use Defer

Add defer to your script tag this will load it after the dom is ready

<script src="game.js" defer></script>

Move the script tag after the canvas

Moving the tag after the canvas will allow the canvas to be ready when the script runs

<canvas id="canvas" width="100" height="320"></canvas>
<script src="game.js"></script>

Wrap your code within the DOMContentLoaded event

Putting your code within this event will run the code after the DOM has loaded.

document.addEventListener('DOMContentLoaded', e => {
  const canvas = document.getElementById('canvas');
  if (canvas != null) {
    ctx = canvas.getContext("2d");
  } else {
    console.log('wtf happen');
  }

  function draw(){
      ctx.background(255,0,0);
  }

})
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338