Javascript Image Resize

前端 未结 13 1505
南旧
南旧 2020-11-28 23:03

Does anyone know how to resize images proportionally using JavaScript?

I have tried to modify the DOM by adding attributes height and width

13条回答
  •  我在风中等你
    2020-11-28 23:44

    I have answered this question here: How to resize images proportionally / keeping the aspect ratio?. I am copying it here because I really think it is a very reliable 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 };
     }
    

提交回复
热议问题