您的位置:首页 > Web前端 > JavaScript

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;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: