2

I'm trying to learn manipulate image and canvas in javascript. I'm wondering why we can not do :

var urlimg='http://images.aviary.com/imagesv5/feather_default.jpg'; 
         var can = document.getElementById('canvas');
         var ctx = can.getContext('2d');
         var img = new Image();
         img.onload = function(){

         }
         img.src =urlimg ;
         can.width = img.width;
         can.height = img.height;
         ctx.drawImage(img, 0, 0, img.width, img.height);
         $('#image1').attr('src', img.src);

And we have to do this :

var urlimg='http://images.aviary.com/imagesv5/feather_default.jpg'; 
         var can = document.getElementById('canvas');
         var ctx = can.getContext('2d');
         var img = new Image();
         img.onload = function(){
             can.width = img.width;
             can.height = img.height;
             ctx.drawImage(img, 0, 0, img.width, img.height);
         }
         img.src =urlimg ;
         $('#image1').attr('src', img.src);

Is it due to time of image to load ?

Can I create a canvas from an existing object image ?

Thanks.

mcbjam
  • 7,344
  • 10
  • 32
  • 40

1 Answers1

1

Is it due to time of image to load ?

Yes in part, but mostly because image loading is asynchronous so the next lines of code are executed right away while the image is loaded. To let you know an event is raised when it's done.

Can I create a canvas from an existing object image ?

No (not directly), but you can draw the image onto a canvas to initialize it (as you already do):

ctx.drawImage(imageElement, 0, 0, width, height);
  • Thanks for your anwser. Are there any difference between an image create like this : var=Image(); and $('#image1') in jquery where 'image1' is the id an img élement : – mcbjam May 19 '13 at 21:59
  • @McbJam If you meant `var el = new Image()`, or in any case if you'd use `document.getElelementById()` they will return the element itself while jQuery's $ returns a *jQuery object* - kind of a wrapped set. See here for some more information: http://stackoverflow.com/questions/1302428/what-does-jquery-actually-return –  May 19 '13 at 23:15