日期:2014-05-17  浏览次数:20735 次

javascript创建图像的一些问题
我用Javascript创建了一些Img标签,成功显示出来后要按比例调整他们大小,在网上参考(好吧直接复制的)了一个函数(ScaleImg),这个函数要三个参数(图像,宽度,高度),可是我用代码创建的Img标签只有src这个属性,那个函数没办法获得图像的原始宽度,高度。该怎么获取呢?或者提供别的思路,感激不尽。


var sum=7;


window.onload=function(){
  for (var i=1;i<sum;i++){
  var img=new Image();
  img.src=i+".jpg";
  document.getElementById("view").appendChild(img);
  ScaleImg(img,200,200);

  }
}
function ScaleImg(Img,ScaleWidth,ScaleHeight){
  var image = new Image();
  image.src = Img.src;
   
  if(image.width > 0 && image.height > 0){
  if(image.width / image.height >= ScaleWidth / ScaleHeight){
  if(image.width > ScaleWidth){
  Img.width = ScaleWidth;
  Img.height = (image.height * ScaleWidth) / image.width;
  }else{
  Img.width = image.width; 
  Img.height = image.height;
  }
  } else{
  if(image.height > ScaleHeight){
  Img.height = ScaleHeight;
  Img.width = (image.width * ScaleHeight) / image.height;
  }else{
  Img.width = image.width; 
  Img.height = image.height;
  } 
  }
  }
 }

------解决方案--------------------
在调用前先定义 全局变量高度 和 宽度, 把 高度 和 宽度 返回(出来) ,在下面直接调用全局变量,不需要一个一个加上高度和宽度