Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'getContext' of null

In my console I get the error: "Uncaught TypeError: Cannot read property 'getContext' of null" and I just can't find the error I've made... or what I've done wrong. So maybe you can help me 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(p.x,p.y,40,Math.PI*2,false); 
    ctx.fill();
}


}

setInterval(draw,30);
like image 326
Pumpkin_M Avatar asked Sep 13 '14 22:09

Pumpkin_M


2 Answers

The error basically means that the HTML and the JavaScript code aren't cooperating properly, or simply that you haven't loaded the script correctly.
Try this:

function init() {
  // Run your javascript code here
}

// Run the 'init' function when the DOM content is loaded
document.addEventListener("DOMContentLoaded", init, false);

Hope this helps.

like image 75
gilbert-v Avatar answered Oct 22 '22 11:10

gilbert-v


The answer is in the comments just after the question! Someone else also posted it as an answer a bit below, but all credits to: @elclanrs

"Right, so the canvas doesn't exist yet. Load the script after the canvas element. – elclanrs Sep 13 '14 at 22:43"

like image 3
Pumpkin_M Avatar answered Oct 22 '22 10:10

Pumpkin_M