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

2
  • 1
    You can try to put script tag under canvas, because the canvas tag has not been rendered yet. Commented Jun 17, 2019 at 3:57
  • var canvas = document.getElementById("canvas"), try replacing with a semicolon var canvas = document.getElementById("canvas"); Commented Jun 17, 2019 at 3:57

2 Answers 2

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...} 
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.