Error canvas.getContext('2d'); | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

10th Oct 2018, 2:52 PM
//pascal_rabbit
//pascal_rabbit - avatar
10 Answers
+ 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
11th Oct 2018, 1:00 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 3
https://code.sololearn.com/W8SYbJ6PjUtP/?ref=app
11th Oct 2018, 1:42 PM
//pascal_rabbit
//pascal_rabbit - avatar
+ 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?
10th Oct 2018, 6:18 PM
//pascal_rabbit
//pascal_rabbit - avatar
+ 2
Hoàng Nguyễn Văn Thanks :) I've fixed it, check out please.
11th Oct 2018, 1:41 PM
//pascal_rabbit
//pascal_rabbit - avatar
+ 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.
10th Oct 2018, 4:41 PM
BraveHornet
BraveHornet - avatar
+ 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
10th Oct 2018, 4:47 PM
//pascal_rabbit
//pascal_rabbit - avatar
+ 1
I changed that line with the one you suggested and know the error says "of undefined" instead of "of null"
10th Oct 2018, 4:51 PM
//pascal_rabbit
//pascal_rabbit - avatar
+ 1
hmmm 🤔 Can you post a link/refference to your complete code?
10th Oct 2018, 4:55 PM
BraveHornet
BraveHornet - avatar
10th Oct 2018, 5:03 PM
//pascal_rabbit
//pascal_rabbit - avatar
+ 1
what src should I write to the script in html?
10th Oct 2018, 5:06 PM
//pascal_rabbit
//pascal_rabbit - avatar