How to resize images proportionally / keeping the aspect ratio?

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

    I think this is a really cool method:

     /**
      * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
      * images to fit into a certain area.
      *
      * @param {Number} srcWidth width of source image
      * @param {Number} srcHeight height of source image
      * @param {Number} maxWidth maximum available width
      * @param {Number} maxHeight maximum available height
      * @return {Object} { width, height }
      */
    function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
    
        var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
    
        return { width: srcWidth*ratio, height: srcHeight*ratio };
     }
    

提交回复
热议问题