Created
May 10, 2017 21:21
Star
You must be signed in to star a gist
Given `container`, find dimensions of `content`. Mimics background-position `contain` or `cover`.
This file contains 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
// 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