图片未加载javascript

时间:2013-08-15 06:14:54

标签: javascript html5 web client-side-scripting

这是我的javascript代码:

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

此代码不起作用图像未显示....我试图跟踪代码,我发现 logoImg.width = 0 logoImg.height = 0 ...任何建议????? 提前谢谢

2 个答案:

答案 0 :(得分:2)

需要等到图像加载完毕,然后才能获得正确的尺寸:

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

在您的情况下,您可能需要检查图片的naturalWidthnaturalHeight,而不仅仅是widthheight

答案 1 :(得分:0)

你可以把时间间隔。 例如:

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