Design & Download
Your JS Library
in Seconds!!!

Snippet: keepAspectRatio()

Written by Christopher West (cwest) on October 16, 2017.
Maximize the dimensions while keeping the same aspect ratio.
function keepAspectRatio(width, height, targetWidth, targetHeight, opt_maximize) {
  targetWidth = Math[opt_maximize ? 'max' : 'min'](targetHeight * width / height, targetWidth);
  return { width: targetWidth, height: targetWidth * height / width };
}

keepAspectRatio() API Documentation

Description

Maximizes the dimensions while keeping the same aspect ratio.

Parameters

  1. width {number}
    The base width.
  2. height {number}
    The base height.
  3. targetWidth {number}
    The target width.
  4. targetHeight {number}
    The target height.
  5. opt_maximize {boolean}
    Optional. Defaults to false. If false-ish, the minimum dimensions will be found where at least one of the dimensions matches the corresponding target dimension. If true-ish, the maximum dimensions will be found where at least one of the dimensions matches the corresponding target dimension.

Returns

Object containing the minimum or maximum calculated width and height while keeping the same aspect ratio provided.
Eg. { height: 400, width: 320 }.

Examples

If you have a picture that has a size of 500 × 400, but you want it to fit in a 300 × 200 box you can use the following to properly adjust the dimensions:

  // Assuming img is an image with a width of 500 and a height of 400
  var dim = YourJS.keepAspectRatio(img.width, img.height, 300, 200);
  img.width = dim.width;   // 250
  img.height = dim.height; // 200
  
If you have a picture that has a size of 500 × 400, but you want the dimensions to be no smaller than a 300 × 200 box you can use the following to properly adjust the dimensions:

  // Assuming img is an image with a width of 500 and a height of 400
  var dim = YourJS.keepAspectRatio(img.width, img.height, 300, 200, true);
  img.width = dim.width;   // 300
  img.height = dim.height; // 240