+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??

4/1/2020 11:19:15 AM

Sohanur Rahman

1 Answer

New 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 }