How to resize images proportionally / keeping the aspect ratio?

前端 未结 18 1692
野趣味
野趣味 2020-11-22 13:58

I have images that will be quite big in dimension and I want to shrink them down with jQuery while keeping the proportions constrained, i.e. the same aspect ratio.

C

18条回答
  •  花落未央
    2020-11-22 14:32

    After some trial and error I came to this solution:

    function center(img) {
        var div = img.parentNode;
        var divW = parseInt(div.style.width);
        var divH = parseInt(div.style.height);
        var srcW = img.width;
        var srcH = img.height;
        var ratio = Math.min(divW/srcW, divH/srcH);
        var newW = img.width * ratio;
        var newH = img.height * ratio;
        img.style.width  = newW + "px";
        img.style.height = newH + "px";
        img.style.marginTop = (divH-newH)/2 + "px";
        img.style.marginLeft = (divW-newW)/2 + "px";
    }
    

提交回复
热议问题