Skip to content

Instantly share code, notes, and snippets.

@handeyeco
Created September 15, 2019 17:38
Show Gist options
  • Save handeyeco/3d00f81d6528b65de1b98cd22c274f53 to your computer and use it in GitHub Desktop.
Save handeyeco/3d00f81d6528b65de1b98cd22c274f53 to your computer and use it in GitHub Desktop.
Contain one aspect ratio within another aspect ratio
/* Simulate object-fit: contain.
* Takes an object's dimension (innerWidth/innerHeight)
* and a container's dimensions (outerWidth/outerHeight)
* and returns a new width/height where the inner object
* will use as much of the container's space as possible
* while respecting the inner object's aspect ratio
*/
function contain(
innerWidth,
innerHeight,
outerWidth,
outerHeight
) {
const innerRatio = innerWidth / innerHeight
const outerRatio = outerWidth / outerHeight
if (innerRatio > outerRatio) {
let scale = outerWidth / innerWidth
return [
outerWidth,
innerHeight * scale
]
} else {
let scale = outerHeight / innerHeight
return [
innerWidth * scale,
outerHeight
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment