+ 2

Canvas question?

When you play around with the examples in a lesson, it works fine. But if try your own it doesn't work. for eg. var c = document.getElementById("canvas"); var ctx=c.getContext("2d"); always results in: cannot read property 'getContext' of null line blahblah Why does this happen?

9th Jun 2018, 8:47 AM
Smithy
Smithy - avatar
10 Answers
+ 7
If you wrote the code in the JS tab, you need to wrap it inside window.onload so that the document is loaded first before the script. window.onload = function(){ var c=document.getElementById("canvas1"); var ctx=c.getContext("2d"); }
9th Jun 2018, 9:09 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 7
should really make a post explaining this issue and how to handle it (with pics) just too lazy ._.
9th Jun 2018, 9:26 AM
Burey
Burey - avatar
+ 6
just added a (long long long) post regarding this issue https://www.sololearn.com/post/7444/?ref=app can also refer to it any other users who encounter this
9th Jun 2018, 1:05 PM
Burey
Burey - avatar
+ 4
Smithy , it's actually a common problem for beginners here on Sololearn. I also struggled about that issue before.😅
9th Jun 2018, 10:54 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 2
Good luck👍
9th Jun 2018, 11:08 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 1
Thank you Jonathan Pizarra I will try that
9th Jun 2018, 10:13 AM
Smithy
Smithy - avatar
+ 1
Jonathan Pizarra glad I'm not the only one. Your solution works fine, now to try some of the other ones they mentioned. I still trying to get a circle to work, but not giving up on it yet😊
9th Jun 2018, 11:07 AM
Smithy
Smithy - avatar
+ 1
Jonathan Pizarra Thanks mate
9th Jun 2018, 11:12 AM
Smithy
Smithy - avatar
+ 1
Burey Thank you
9th Jun 2018, 1:56 PM
Smithy
Smithy - avatar
0
Burey it could be handy, or maybe I'm the only one having trouble with it 😂😂😂
9th Jun 2018, 10:16 AM
Smithy
Smithy - avatar