Skip to content

Instantly share code, notes, and snippets.

@DimitryDushkin
Last active January 21, 2018 17:48
Show Gist options
  • Save DimitryDushkin/bd4b2ae56fb9b97a8ab6bcdc39afdb85 to your computer and use it in GitHub Desktop.
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
// @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