Created
September 15, 2019 17:38
-
-
Save handeyeco/3d00f81d6528b65de1b98cd22c274f53 to your computer and use it in GitHub Desktop.
Contain one aspect ratio within another aspect ratio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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