Can't read getContext property... | Sololearn: Learn to code for FREE!
+ 3

Can't read getContext property...

<canvas id="canvas"></canvas> In javascript When I am trying this... var canvas= document.getElementById('canvas'); var ctx= canvas.getContext('2d'); It is showing me an error message that it can't read getContext...why it's happening Will you please tell me where am I going wrong

6th Feb 2019, 8:34 PM
Prabhat Kumar Singh
Prabhat Kumar Singh - avatar
5 Answers
+ 3
// You haven't use "window.onload" to get a context for the canvas. For example : https://code.sololearn.com/Wp7VT4YaZJgg/?ref=app https://code.sololearn.com/WZXfgNIuw41S/?ref=app
6th Feb 2019, 8:50 PM
program
program - avatar
+ 4
//it's seems no problem here. //Can you attach full source code so we can look further in codes
6th Feb 2019, 8:39 PM
Sudarshan Rai
Sudarshan Rai - avatar
+ 3
Make sure than getElementById return the canvas element and not null (eg. call js after browser load canvas and not before)
6th Feb 2019, 8:45 PM
KrOW
KrOW - avatar
+ 3
Is it necessary to add window.onload everytime
7th Feb 2019, 2:46 AM
Prabhat Kumar Singh
Prabhat Kumar Singh - avatar
+ 2
Its not necessary use window.onload though its used often... The important is than you get a reference to an element AFTER its loaded by browser else you will get a null reference. This is source of confusion among many users, above all on SL where the content of JS tab is inserted into head element of final generated html file then, get a reference DIRECTLY inside it, you will get a null ref... Read and observe this code for understand https://code.sololearn.com/WlA8Fx8bl6nI/?ref=app
7th Feb 2019, 12:31 PM
KrOW
KrOW - avatar