Calculate aspect ratio conserving resize for images in Javascript

This is one way to do it. As a bonus no ifs needed.

      * Resize arbitary width x height region to fit inside another region.
      * Conserve aspect ratio of the orignal region. Useful when shrinking/enlarging
      * images to fit into a certain area.
      * @param {Number} srcWidth Source area width
      * @param {Number} srcHeight Source area height
      * @param {Number} maxWidth Fittable area maximum available width
      * @param {Number} srcWidth Fittable area maximum available height
      * @return {Object} { width, heigth }
     calculateAspectRatioFit : function(srcWidth, srcHeight, maxWidth, maxHeight) {

        var ratio = [maxWidth / srcWidth, maxHeight / srcHeight ];
        ratio = Math.min(ratio[0], ratio[1]);

        return { width:srcWidth*ratio, height:srcHeight*ratio };

 Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

2 thoughts on “Calculate aspect ratio conserving resize for images in Javascript

  1. Why create an array first ? Couldn’t the two first lines be replaced by :

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);


  2. It is wrong

    originalwidth 3458
    originalHeight 1271

    aspect ratio = 2:9

    srcWidth = window.innerwidth
    srcHeight = window.innerHeight
    maxWidth = originalwidth
    maxHeight = originalHeight

    Object {width: 1219.625386996904, height: 819}

    aspect ration is 1:4

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>