Js图片等比例缩放

    
<img src="chargein_cashgift_detail.png" class="img" alt="">

function showImg(img,maxW,maxH) {
    let objImg = new Image();
    let w,h,wRatio,hRatio;
    let Ratio =1; //比率
    objImg.src=img.src;
    if(img.naturalWidth){
        w =img.naturalWidth;
        h =img.naturalHeight;
    }else{
        w =objImg.width;
        h =objImg.height;
    }
    wRatio = maxW / w;
    hRatio = maxH / h;
    if(maxW === 0 && maxH ===0){
        Ratio = 1;
    }else if(maxW === 0){
        if(hRatio<1) {
            Ratio = hRatio;
        }
    }else if (maxH === 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;
    }
    img.width =w;
    img.height =h;
    console.log(w)
    console.log(h)
}
let img1 =document.querySelectorAll('img')[0]
showImg(img1,300,200)
View Code

 

posted @ 2017-09-22 18:01  浮生如梦似离殇  阅读(121)  评论(0编辑  收藏  举报