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..

19th Dec 2017, 7:26 PM
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė…
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė… - avatar
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"); }
19th Dec 2017, 8:04 PM
Duncan
Duncan - avatar
+ 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.
19th Dec 2017, 7:49 PM
Jonas SchrÃļter
Jonas SchrÃļter - avatar
+ 1
thanks, already found fix and used jquery $(document).ready
19th Dec 2017, 8:01 PM
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė…
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė… - avatar
+ 1
Thanks for answers!
19th Dec 2017, 8:29 PM
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė…
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė… - avatar
+ 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.
19th Dec 2017, 8:43 PM
Hassie
Hassie - avatar
0
cannot read property getContext of null
19th Dec 2017, 7:27 PM
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė…
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė… - avatar
0
Good to know :)
19th Dec 2017, 8:52 PM
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė…
aĖ˛Ė…dĖ˛Ė…rĖ˛Ė…nĖ˛Ė… - avatar