How to resize images proportionally / keeping the aspect ratio?

前端 未结 18 1861
野趣味
野趣味 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:30

    In order to determine the aspect ratio, you need to have a ratio to aim for.

    Height

    function getHeight(length, ratio) {
      var height = ((length)/(Math.sqrt((Math.pow(ratio, 2)+1))));
      return Math.round(height);
    }
    

    Width

    function getWidth(length, ratio) {
      var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
      return Math.round(width);
    }
    

    In this example I use 16:10 since this the typical monitor aspect ratio.

    var ratio = (16/10);
    var height = getHeight(300,ratio);
    var width = getWidth(height,ratio);
    
    console.log(height);
    console.log(width);
    

    Results from above would be 147 and 300

提交回复
热议问题