0
Why this code is'nt working
var canvas = document.querySelector("canvas"); var c = canvas.getContext("2d"); why it isnt working? I have <canvas> tag in my html code..
7 Answers
+ 4
As Jonas mentioned, maybe your html hasn't loaded so the script cannot fine the canvas. I have used the window.onload method with success:
window.onload = function(){ // this ensures your script will only run once the window (html) has loaded.
// your code - I haven't used querySelector so not sure if it's should work?
var canvas = document.querySelector("canvas");
var c = canvas.getContext("2d");
// my code uses getElementById
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
}
+ 4
Maybe your html isn't loaded when your code tries to read it's value. Use setTimeout (func (){//code}, 100) to let your script wait to let the html load.
+ 1
thanks, already found fix and used jquery $(document).ready
+ 1
Thanks for answers!
+ 1
Another way is to use the defer attribute when you import your JS in your HTML <script src="path" defer> This will run the JS once the HTML DOM has loaded.
0
cannot read property getContext of null
0
Good to know :)