Canvas type error | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Canvas type error

This is my code <html> <head></head> <body> <canvas id="canvas1" width="1000" height="1000"> </canvas> <script> var c=document.getElementById("canvas1"); var ctx=c.getContext("2d"); ctx.fillRect(20,20,100,100); </script> </body> </html> When I try to run it I get a type error "null not an object (evaluating 'c.getContext')

26th Feb 2018, 2:52 PM
Jack Leonard
Jack Leonard - avatar
1 Answer
+ 5
Write the whole script tag outside the body tag. Or write everything in a function like this: window.onload =function(){ // code } This is because JS loads before the DOM tree so when JS is loaded, canvas is undefined
26th Feb 2018, 4:17 PM
Gami
Gami - avatar