Uncaught TypeError: Cannot read property 'getContext' from null

In my console, I get the error message: "Uncaught TypeError: Cannot read the getContext property" null "and I just can’t find the error I made ... or what I did wrong. So maybe you can help can I find it? Please help :)

enter code here var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var cW = canvas.width = 1000; var cH = canvas.height = 500; var particleAmount = 10; var particles = []; for(var i=0;i<particleAmount;i++) { particles.push(new particle()); } function particle() { this.x = (Math.random() * (cW-(40*2))) + 40; this.y = (Math.random() * (cH-(40*2))) + 40; this.xv = Math.random()*20-10; this.yv = Math.random()*20-10; } function draw () { ctx.fillStyle = "black"; ctx.fillRect(0,0,cW,cH); for(var ii=0;ii<particles.length;ii++){ var p = particles[ii]; ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(px,py,40,Math.PI*2,false); ctx.fill(); } } setInterval(draw,30); 
+5
source share
5 answers

Answer in the comments immediately after the question! Someone else also posted it as an answer just below, but all the credits: @elclanrs

"That's right, so the canvas does not exist yet. Download the script after the canvas element. - elclanrs Sep 13 '14 at 22:43"

+3
source

The error basically means that the HTML and JavaScript code are not interacting properly, or simply that you did not load the script correctly.
Try the following:

 function init() { // Run your javascript code here } document.addEventListener("DOMContentLoaded", init, false); 

Hope this helps.

+5
source

I think you put the script tag above the canvas tag, put it after the canvas tag.

+1
source

Place the script file after the canvas. This means that you put your script before the body tag.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HTML5 Canvas</title> <link rel="shortcut icon" href="assets/1.png"> <link rel="stylesheet" href="assets/canvas.css"> </head> <body> <div class="container"> <h2>Canvas</h2> <canvas id="myCanvas" width="400" height="300"> </canvas> <!-- End Canvas --> </div> <!-- End Container --> <script src="canvas.js"></script> </body> </html> 
0
source

Try declaring the canvas element before the script tag. It worked for me.

-1
source

Source: https://habr.com/ru/post/1202512/


All Articles