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+

One thought 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);

    Vicne

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=""> <strike> <strong>