美文网首页JS
JS 按比例自定义缩放图像

JS 按比例自定义缩放图像

作者: 五岁小孩 | 来源:发表于2020-07-25 22:19 被阅读0次

    <center><font size='5' color='#fff'>按比例自定义缩放图像</font></center>

    • img调用

      错误图像显示: onerror="onerror=null;src='/imgError.jpg'"

      <img onload="AutoResizeImage(100,100,this)" 
           onerror="onerror=null;src='/imgError.jpg'"
           class="rounded" src="/demo.jpg" alt="">
      
    • js

      //按比例缩放图像
      function AutoResizeImage(maxWidth,maxHeight,objImg){
        var img = new Image();
        img.src = 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.height = h;
        objImg.width = w;
      }
      

    相关文章

      网友评论

        本文标题:JS 按比例自定义缩放图像

        本文链接:https://www.haomeiwen.com/subject/elhvlktx.html