Last active
January 21, 2018 17:48
-
-
Save DimitryDushkin/bd4b2ae56fb9b97a8ab6bcdc39afdb85 to your computer and use it in GitHub Desktop.
Get width and height of item with fixed aspect ratio fitted in arbitrary container
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
// @flow | |
type Size = { width: number, height: number }; | |
function getFittedSlideSize(container: Size, target: Size): Size { | |
const targetAspectRatio = target.width / target.height; | |
const containerAspectRatio = container.width / container.height; | |
// if aspect ratio of target is "wider" then target's aspect ratio | |
const fit = targetAspectRatio > containerAspectRatio | |
? 'width' // fit by width, so target's width = container's width | |
: 'height'; // fit by height, so target's height = container's height | |
return { | |
width: fit === 'width' | |
? containerWidth | |
: Math.round(containerHeight * ( target.width / target.height)), | |
height: fit === 'height' | |
? containerHeight | |
: Math.round(containerWidth * (target.height / target.width)), | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment