js 自动缩放图片居中

  • Post author:
  • Post category:其他


// 缩放图片,imgSrc用户延迟加载图片url

function AutoResizeImage(maxWidth,maxHeight,objImg,imgSrc){

var img = new Image();

img.src = imgSrc || objImg.src;

var hRatio;

var wRatio;

var Ratio = 1;

var w = img.width;

var h = img.height;

wRatio = maxWidth / w;

hRatio = maxHeight / h;

if (maxWidth ==0 && maxHeight==0){

Ratio = 1;

}else if (maxWidth==0){

if (hRatio<1) Ratio = hRatio;

}else if (maxHeight==0){

if (wRatio<1) Ratio = wRatio;

}else if (wRatio<1 || hRatio<1){

Ratio = (wRatio<=hRatio?wRatio:hRatio);

}

if (Ratio<1){

w = w * Ratio;

h = h * Ratio;

}

objImg.style.height = Math.round(h) + “px”;

objImg.style.width = Math.round(w) + “px”;

if(h < maxHeight) { // 纵向有空余空间

objImg.style.marginTop = Math.round((maxHeight – h) / 2) + “px”;

}

if(w < maxWidth) { // 横向有空余空间

objImg.style.marginLeft = Math.round((maxWidth – w) / 2) + “px”;

}

if(!!!objImg.src)

objImg.src = imgSrc;

}



版权声明:本文为boolbo原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。