0

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks alot for your help ... but i have tried your idea and replaced my code with your modified one with onload function but this didn't work also i think i had error because all code after that didn't work
@AhmedGhazy So check it line after line , clean it to find the reason , and use browser` console to see errors
0

You can put a time Interval. Eg :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.