Zu007
Zu007

Reputation: 81

variable Scope out side the Method

i cann't understand how it's Possible. These properties assign out side the method (image.onload=function())& after method write..

image.src="barn.jpg";
canvas.width=500;

but using these Properties inside the method.what about variable Scope for it?

 var canvas=document.getElementById("myConvas");
                    var ctx=canvas.getContext("2d");

                    var image=new Image();

                    image.onload=function(){

                        ctx.drawImage(image,0,0,canvas.width,canvas.height);

                    }
                    image.src="barn.jpg";
                    canvas.width=500;

Upvotes: 0

Views: 31

Answers (1)

markE
markE

Reputation: 105015

image.src causes barn.jpg to begin downloading, but the browser will also continue executing all code following image.src.

So while the image is downloading, the browser also executes canvas.width=500.

After the image has fully loaded, it goes back and executes any code inside the image.onload function.

So your code actually executes in this order:

  1. var canvas=document.getElementById("myConvas");
  2. var ctx=canvas.getContext("2d");
  3. var image=new Image();
  4. The browser makes a note to call image.onload when the image is fully loaded. But the browser does not actually execute the .onload code yet.
  5. image.src="barn.jpg";
  6. canvas.width=500;
  7. ctx.drawImage(image,0,0,canvas.width,canvas.height);

Upvotes: 1

Related Questions