+ 1
Error canvas.getContext('2d');
Im writing a code for a game and when creating a canvas for 2d theres this error: Uncaught TypeError: Cannot read property 'getContext' of null Line: 4 I think the problem is here. const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); Any thoughts?
10 ответов
+ 2
This is an issue with how SoloLearn includes the JS script, which was discussed before, and can be fixed with either window.onload or by declaring the script at the bottom of the HTML file.
https://www.sololearn.com/Discuss/1397493/code-works-on-my-computer-but-won-t-run-on-the-sololearn-ide
https://www.sololearn.com/Discuss/1260302/help-needed-javascript-onload-and-code-readability
+ 3
https://code.sololearn.com/W8SYbJ6PjUtP/?ref=app
+ 2
Hornetfly I have tried making a similar program both in sololearn editor and notepad ++ and while the notepad version worked perfectly in browser, the sololearn version had an error. Isn't that cool?
+ 2
Hoàng Nguyễn Văn Thanks :)
I've fixed it, check out please.
+ 1
It's all right, so the error is in the html.
Do you have an <canvas> tag in you html file with the id="canvas" attribute?
like <canvas id="canvas"></canvas>
If not, pls correct it
EDIT: You can also do
const context=document.getElementsByTagName("canvas")[0].getContext("2d");
so if you don't want to use the id attribute.
+ 1
There is a canvas tag in the html
I have tried launching it from my phone and now the error comes at another line, trying to figure out
On PC it's alerting about the context which is really weird
+ 1
I changed that line with the one you suggested and know the error says "of undefined" instead of "of null"
+ 1
hmmm 🤔
Can you post a link/refference to your complete code?
+ 1
what src should I write to the script in html?