+ 1

Cannot read property "getContext" of null

I don't understand why my script in the script tag but gives me an error when it's in the JavaScript window... Please, help <3

24th Aug 2018, 6:54 PM
Thomas Teixeira
Thomas Teixeira - avatar
12 Respostas
+ 3
this might help in addition to KrOW's explanation https://www.sololearn.com/post/7444/?ref=app
24th Aug 2018, 11:22 PM
Burey
Burey - avatar
+ 5
2:42 in Israel.... good night for reals now >:D
24th Aug 2018, 11:43 PM
Burey
Burey - avatar
+ 3
First you should post your code here, than we will see ^^
24th Aug 2018, 6:56 PM
BraveHornet
BraveHornet - avatar
+ 3
and guess what time it is now KrOW.... heading quite close to 3am again o_O
24th Aug 2018, 11:36 PM
Burey
Burey - avatar
+ 2
Thomas Teixeira Like i thinked you have called getContext on null object because getElementById has returned null... This happen on SL because all js writed in JS tab is inserted in a script tag inside head tag then BEFORE document is loaded (then you get null from getElementById). You can resolve by calling getElementById AFTER your elemnt is loaded (inserting js content in tag at bottom of document) or using window.onload in js tab. I hope that i am been clear 😉
24th Aug 2018, 11:09 PM
KrOW
KrOW - avatar
+ 2
Basically (in your case) you have to wait for your element to be loaded (after this you can sefetly get a reference to it with js)... Then or you insert your js code after you element inside a script tag (then in html tab), or assign a function that do this to window.onload (you can use event listeners also but for this window.onload its good) at example: window.onload= function(){ var can = document.getElementById("screen"); var ctx = can.getContext("2d"); ctx.fillRect(10, 10, 10, 10); } Warn to get right scope for vars P.S. Read Burey feed that contain useful info about this common errors
24th Aug 2018, 11:37 PM
KrOW
KrOW - avatar
+ 1
I am sure that your canvas element its not loaded at getElementById (or similar) call time
24th Aug 2018, 7:43 PM
KrOW
KrOW - avatar
+ 1
Yes sorry, here it is, thanks for your help https://code.sololearn.com/W1KrHNDRYNA5/?ref=app There is a part of the same code in a script tag, that was for test :)
24th Aug 2018, 10:45 PM
Thomas Teixeira
Thomas Teixeira - avatar
+ 1
Thank you a lot to you two <3 So I can call my JavaScript in the bottom of document, but what would be is name in order to link it Or I could just initialize it and wait for my web page to be fully loaded, am I right ? Thank you again ♄
24th Aug 2018, 11:31 PM
Thomas Teixeira
Thomas Teixeira - avatar
+ 1
Burey Yes, i remember .... Above all the 3:00 am work 😁😁😁👍👍
24th Aug 2018, 11:31 PM
KrOW
KrOW - avatar
+ 1
Burey 😂😂😂😂... In Italy now its 01:37 AM 😝
24th Aug 2018, 11:37 PM
KrOW
KrOW - avatar
0
Good night đŸ˜ȘđŸ˜ȘđŸ˜Ș
24th Aug 2018, 11:44 PM
KrOW
KrOW - avatar