0

这是我的 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=0logoImg.height=0 ...有什么建议吗??????提前致谢

4

2 回答 2

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

并且可能在您的情况下,您需要检查图像的naturalWidthandnaturalHeight而不仅仅是widthand height

于 2013-08-15T06:18:23.193 回答
0

你可以设置一个时间间隔。例如:

setTimeout(function(){whatever you want to do here},3000);
于 2013-08-15T07:46:05.950 回答