Why script for canvas is not working? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why script for canvas is not working?

I connected script.js file to main html file.. I wrote document.write("hi"); It worked. Than i created a canvas field in html. Than i tried to creat a rectangle there using javascript.. But when i wrote the code on script.js file, it doesn't work. But when i cut that and paste it inside the main html file and put that inside <script> It works. Why can't i do that on script.js file as an external code instead of internal code??

1st Apr 2020, 11:19 AM
Sohanur Rahman
Sohanur Rahman - avatar
1 Answer
+ 4
With an external script, chances are that the script was executed before the DOM had been fully loaded, so it was unable to operate on the <canvas> element because it didn't exist yet when the script ran. Make sure the DOM has loaded before operating on it by wrapping the parts of your script that work with HTML elements inside window.onload(), e.g. window.onload = () => { // get canvas element and draw on it }
1st Apr 2020, 11:42 AM
Shadow
Shadow - avatar