calculates widths/heights according to common ratios.
what's an aspect ratio *really*?
well, i'm actually not quite sure.
…
But fitting things using math,
just seems to be nice
and nobody knows why.
🌴
npm i fit-aspect-ratio
const aspect = require('fit-aspect-ratio')
//calculate a missing width/height
aspect({ratio:'3:4', width:640})
// {width:300, height:480}
aspect({ratio:'widescreen', height:400}) // (2.35:1)
// {width:940, height:400}
//fit to the closest aspect ratio
let res = aspect({
width: 1280,
height: 722 // (almost 1280×720 )
})
// { closest:
// { names: [ '16:9', ... ],
// description: 'HD video',
// decimal: 1.77777 },
// width: 1280,
// height: 720
// }
// force a specific aspect ratio (assumes landscape)
aspect({ratio:'3:4', height:640, orientation:'portrait'}) //essentially '4:3'
// {width:480, height:640}
<script src="https://unpkg.com/fit-aspect-ratio/builds/fit-aspect-ratio.js"></script>
<script>
fitAspect({ratio:'A4', height:8.5, orientation:'landscape'})
</script>
you can see the list of aspect-ratios we use here
when fitting to an aspect ratio, height
is adjusted, not width. (..scrolling down is easier?) This can be configured in future versions.
Demo
ok, ELI5 aspect-ratio
ratios are (typically) given as width:height
suppose our computer screen is 4:3
, our resolution could be 640x480
.
To calculate:
// get a decimal representation
let decimal= 4/3 // 1.3333333
// this can get us our width..
width = 480 * decimal
// 640
// to get height, flip numerator/denominator
let inverse = 1/decimal // or '3/4'
height = 640 * inverse
// 480
this took me a good while...
See also:
- aspect-crop - cropping images based on this library
MIT