Skip to content

Instantly share code, notes, and snippets.

@SaFrMo
Created May 10, 2017 21:21
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save SaFrMo/48d6a3725d2dc7728e4d53527cc33ee5 to your computer and use it in GitHub Desktop.
Given `container`, find dimensions of `content`. Mimics background-position `contain` or `cover`.
// Given `container`, find dimensions of `content`. Mimic either CSS background-position `contain` or `cover`.
// Both `container` and `content` must have height and width attributes.
// aspect ratio > 1: image is portrait
// aspect ratio < 1: image is landscape
const contain = ( contents, container ) => {
// thanks to http://stackoverflow.com/questions/27939971/difference-between-background-sizecover-and-background-sizecontain
const contentsAspectRatio = contents.width / contents.height
const containerAspectRatio = container.width / container.height
if( containerAspectRatio > contentsAspectRatio ){
return {
height: container.height,
width: container.height * contentsAspectRatio
}
} else {
return {
width: container.width,
height: container.width / contentsAspectRatio
}
}
}
const cover = ( contents, container ) => {
const contentsAspectRatio = contents.width / contents.height
const containerAspectRatio = container.width / container.height
if( containerAspectRatio > contentsAspectRatio ){
return {
width: container.width,
height: container.width / contentsAspectRatio
}
} else {
return {
height: container.height,
width: container.height * contentsAspectRatio
}
}
}
export default {
contain: contain,
cover: cover
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment