Image isn't loaded javascript

86 Views Asked by At

here is my javascript code :

> var logoImg = new Image();
> logoImg.src = '../img/smiley.png';
> 
> // Store the original width value so that we can keep the same width/height ratio later
>   var originalWidth = logoImg.width;
> 
>   // Compute the new width and height values
>   logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
>   logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth);
> 
> // Create an small utility object
>   var logo = {
                 img : logoImg,
>            x : (canvas.width / 2) - (logoImg.width / 2),
>             y : (canvas.height / 2) - (logoImg.height / 2)
>       }
> 
>   // Present the image
>   c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);

this code doesn't work the image isn't displayed .... i tried to trace the code and i found that the logoImg.width=0 and logoImg.height=0 ... any suggestions????? thanks in advance

2

There are 2 best solutions below

0
On

You can put a time Interval. Eg :

setTimeout(function(){whatever you want to do here},3000);
2
On

Need to wait until image is loaded, then you will get its correct dimensions:

var logoImg = new Image();
logoImg.src = '../img/smiley.png';
logoImg.onload = function(){
   var originalWidth = logoImg.width;
   logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
   logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth); 
   var logo = {
           img : logoImg,
           x : (canvas.width / 2) - (logoImg.width / 2),
           y : (canvas.height / 2) - (logoImg.height / 2)
       }
   c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);
}

And may be in your case you will need to check image's naturalWidth and naturalHeight instead of just width and height.