码迷,mamicode.com
首页 > Web开发 > 详细

Js图片等比例缩放

时间:2017-09-22 19:06:59      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:比例   nbsp   cas   image   wim   pre   bsp   分享   ==   

技术分享
    
<img src="chargein_cashgift_detail.png" class="img" >

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

 

Js图片等比例缩放

标签:比例   nbsp   cas   image   wim   pre   bsp   分享   ==   

原文地址:http://www.cnblogs.com/vhen/p/7576229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!