Calculate maximum image for given container size

author's avatar
Kees de Kooter
Mar 16 20:11

An algorithm for fitting an image into a container, keeping original aspect ratio, maximizing image size in the available box.

const sourceRatio = originalImageWidth / originalImageHeight
const targetRatio = containerWidth / containerHeight

if (sourceRatio > targetRatio) {
  imageWidth = containerWidth
  imageHeight = Math.round(containerWidth * sourceRatio)
} else {
  imageWidth = Math.round(containerHeight * sourceRatio)
  imageHeight = containerHeight
}

Credits to Andrew Shepherd https://stackoverflow.com/a/15398653/26496