0

I have set up a canvas in HTML5 exactly right (I think) I've got an error:

I've previously made a canvas game, and I have copied and pasted the code multiple times, It looks right to me, I've googled the HTML canvas set up, I have got the same answer, please help!

<html>
<head>
</head>
<body>
    <script src="jumpMan.js"></script>
    <canvas width="1000px" height="450px" id="canvas"></canvas>

</body>
</html>

//jumpMan.js
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
ctx.fillRect(50,50,50,50);

My Error:

Uncaught TypeError: Cannot read property 'getContext' of null at jumpMan.js:3 (anonymous) @ jumpMan.js:3

Kaiido
  • 123,334
  • 13
  • 219
  • 285
Oli.W
  • 3
  • 1
  • 1
    You can try to put script tag under canvas, because the canvas tag has not been rendered yet. – Clark Jun 17 '19 at 03:57
  • var canvas = document.getElementById("canvas"), try replacing with a semicolon var canvas = document.getElementById("canvas"); – Moshe Sommers Jun 17 '19 at 03:57

2 Answers2

1

Your problem is that your content isn't rendered yet.

So you have to check if your content/document is rendered before accessing the DOM.

Try this:

document.addEventListener('DOMContentLoaded', fn, false) ;
function fn() { //get canvas access...} 
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Sv3n
  • 347
  • 2
  • 6
  • 20
0

I've recently found out something else that also works: If you move the tags under the tag, it will work.

<canvas width="1000px" height="450px" id="canvas" ></canvas>
<script src='jumpMan.js'></script>
Oli.W
  • 3
  • 1