Skip to content

Instantly share code, notes, and snippets.

@mattkenefick
Created November 27, 2023 21:11
Show Gist options
  • Save mattkenefick/d84a674fc3c27b5355dbb1af740b2fd3 to your computer and use it in GitHub Desktop.
Save mattkenefick/d84a674fc3c27b5355dbb1af740b2fd3 to your computer and use it in GitHub Desktop.
/**
* Usage:
*
* const ratio = approximateAspectRatio(855, 482, 20);
* // "16:9"
*
* @param number width
* @param number height
* @param number maxRatio
* @return string
*/
function approximateAspectRatio(width, height, maxRatio = 20) {
const targetRatio = width / height;
let closestRatio = '';
let closestRatioDifference = Infinity;
for (let i = 1; i <= maxRatio; i++) {
const j = Math.round(i / targetRatio);
const ratio = i / j;
const difference = Math.abs(targetRatio - ratio);
if (difference < closestRatioDifference) {
closestRatioDifference = difference;
closestRatio = `${i}:${j}`;
}
}
return closestRatio;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment