前几天到网上搜了一个用来缩放图片的程序,结果发现有时候图片会变的很小,要重新刷新一下才会变成合适的大小,觉得很纳闷,也没找出原因.干脆就又到网上搜了一个,这次是老外写的一个,感觉代码少了好多,效果还不错,代码如下:
原来的:
function drawImage(imgD, maxW, maxH) {
if(!imgD)return;
var image = new Image();
image.src = imgD.src;
var dW=imgD.width;
var dH=imgD.height;
if(dW>maxW||dH>maxH){
var rationW=dW/maxW;
var rationH=dH/maxH;
if(rationW<rationH)rationW=rationH;
dW=dW/rationW;
dH=dH/rationW;
if(dW>0&&dH>0){
imgD.width=dW;
imgD.height=dH;
}
}
新搜到的:
function scaleImage(img,v) {
if(!img)return;
floorSize = .26;
ceilingSize = 1.0;
v = floorSize + (v * (ceilingSize - floorSize));
img.style.width = (v*190)+'px';
}
综合一下,得到:
function scaleImage(img,maxW,maxH) {
if (!img) return;
var dW=img.width;
var dH=img.height;
if(dW>maxW||dH>maxH){
var rationW=dW/maxW;
var rationH=dH/maxH;
if(rationW<rationH)rationW=rationH;
dW=dW/rationW;
dH=dH/rationW;
if(dW>0&&dH>0){
img.style.width =dW+"px";
img.style.height =dH+"px";
}
}
}