+ 4

Why even the simplest <canvas> isn't working?

by simplest I mean the basic example given in the HTML5 code sample https://code.sololearn.com/Wf1qfOqWeSya/# tried this from Firefox on my computer, VS Code, SoloLearn (web and app) and even Firefox Android

12th Jul 2020, 6:39 PM
tebkanlo
tebkanlo - avatar
5 odpowiedzi
+ 9
There is nothing wrong in your code. You have successfully retrieved the canvas element and its 2d drawing context. Now you just need to start drawing. Example: ctx.fillStyle = "red"; ctx.fillRect(0,0,100,100);
12th Jul 2020, 7:09 PM
Kevin ★
+ 5
Enter this in CSS part and see magic canvas { background-color:green; }
12th Jul 2020, 8:26 PM
Oma Falk
Oma Falk - avatar
+ 4
tebkanlo So you are saying that your code is only working when you paste it in body tag (between script tags)? This happens because you need to wait for DOM loading before using the DOM related objects in your Javascript. Codes in the head tag run before body (and canvas) loading. Solutions: 1- Load your external js file after canvas loads (using script in body tag). <body> <canvas ....></canvas> <script src="script.js"></script></body> 2- Use onload event to run your DOM related code when element loads. In Sololearn codes in JS tag are considered as part of the head tag. Use window.onload: https://www.sololearn.com/post/90825/?ref=app
12th Jul 2020, 10:54 PM
Kevin ★
+ 3
Kevin ★ Thanks for sharing
13th Jul 2020, 9:48 AM
tebkanlo
tebkanlo - avatar
+ 2
Thanks for your replies, apparently whatever I had added after the 'var ctx = can.getContext("2d");' is not present here, because I forgot to save it. So I forced myself to rember what I had written before and it didn't work that too, Figure it out: it was all written inside the 'script.js' file. Just a quick copy paste between <script> ... </script> in the html file and it works flawlessly. https://code.sololearn.com/Wx1fo2350WvN/# I don't recall it was ever written anywhere that it has to be in the '.html' I even had other java scripts functions saved in that script.js file and they're working just fine with onclick events. Anyway thanks again, and goodnight
12th Jul 2020, 9:55 PM
tebkanlo
tebkanlo - avatar