js 自动缩放图片居中
2016-12-26 13:40
405 查看
// 缩放图片,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;
}
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;
}
相关文章推荐
- 图片自动缩放 js图片缩放
- css 图片水平居中+自动等比例缩放
- JS+css 图片自动缩放自适应大小
- js 最完美解决 图片在图片框内按宽高比例自动缩放
- js+css图片自动等比例缩小且垂直居中
- 通过Js自动按比例缩放图片
- android开发之图片的浏览、缩放、拖动及自动居中
- 纯JS实现图片预览与等比例缩放和居中
- js+css图片自动等比例缩小且垂直居中[v20071208]
- js控制图片缩放、水平和垂直方向居中对齐
- 图片预加载并且自动等比例缩放的JS插件[转]
- js控制图片缩放、水平和垂直方向居中对齐
- 图片的浏览、缩放、拖动和自动居中
- Android 图片的浏览、缩放、拖动和自动居中
- [转]图片自动缩放 js图片缩放
- 共享一个ASP里的图片自动缩放的JS
- android 图片的浏览、缩放、拖动和自动居中示例
- android 图片的浏览、缩放、拖动和自动居中示例
- Android 图片的浏览、缩放、拖动和自动居中
- js控制图片缩放、水平和垂直方向居中对齐