简体   繁体   中英

Create Canvas from image on javascript

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM