0

So I have this really basic js script linked in the HTML, it gives no errors when i try to run it but it just doesn't do what it's supposed to. Here's the code:

var canvas = document.getElementById("canvas"),
  c = canvas.getContext("2d"),
  width = canvas.width = window.innerWidth,
  height = canvas.height = window.innerHeight;
c.fillRect(0, 0, 50, 50);
<!DOCTYPE html>
<html>

<head>
  <script type='text/javascript' src='main.js'></script>
</head>

<body>
  <canvas id='canvas'></canvas>
</body>

</html>

This should just draw a square in the top-left corner, but it does nothing. It was originally a quite large file, but i reduced it to this just as a proof of concept. As you can see, the snippet works, but chrome doesn't.

Peeyush Kushwaha
  • 2,995
  • 6
  • 29
  • 61
lenerdv
  • 125
  • 12

1 Answers1

1

your script is launched before the declaration of the canvas. At the time of script launch your canvas dom object is not defined. In addition, change type to text/javascript. Change to this :

<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <canvas id='canvas'></canvas>
  <script type='text/javascript' src='main.js'></script>
</body>

</html>
Daphoque
  • 3,588
  • 1
  • 13
  • 22
  • Your diagnosis is correct, but you should also educate OP about `DOMContentLoaded` state, which is purpose-built for exactly this – Peeyush Kushwaha Mar 07 '20 at 21:01
  • This worked, but I also found that adding `defer` to the script is a valid solution and lets me keep `script` elements in the `head` – lenerdv May 03 '21 at 11:21