Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 657
mcbjam Avatar asked Jul 15 '26 09:07

mcbjam


1 Answers

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!