spabsa
spabsa

Reputation: 151

Why must I use window.onload to draw an image to the canvas

I'm trying to draw an image to the canvas but the code:

ctx.drawImage(ground, 0, 0);

doesn't work by itself. It was pointed out to me that its because the html wasn't loaded when that line was executed. I was suggested this code, which works:

window.onload = function(){
    ctx.drawImage(ground, 0, 0);
}

I don't understand why this works though because I thought a similar solution would be to place the script tag below the body which I did but that doesn't work. Can someone explain this to me in a way a toddler could understand.

Upvotes: 1

Views: 1563

Answers (1)

ellipsis
ellipsis

Reputation: 12152

First things first, in a web page the JavaScript executes first, then the text in body loads later. So placing <script> tag anywhere syntactically won't matter as it will load first. The ctx.drawImage(ground, 0, 0); runs before the page has even rendered so you cannot see the output.

Window.onload is a method which runs the function inside it after the whole document has rendered. After it is rendered and you run your function you will see the desired output.

Upvotes: 1

Related Questions