Skip to content

Instantly share code, notes, and snippets.

@willcode4food
Last active August 29, 2019 13:59
Show Gist options
  • Save willcode4food/d7bf664c34378429ce8680e8d38c50b5 to your computer and use it in GitHub Desktop.
Save willcode4food/d7bf664c34378429ce8680e8d38c50b5 to your computer and use it in GitHub Desktop.
Calculate Dynamic Aspect Ratio
// Thanks Kyle Mavis!!
const calcViewBox = ({width=0, heigth=0, baseWidth=0, baseHeight=0}) => {
const defaultAspect = baseWidth / baseHeight;
const targetAspect = width / height;
if (targetAspect > defaultAspect) {
const height = baseHeight * (defaultAspect / targetAspect);
const y = (baseHeight - height) / 2;
return `0 ${y} ${baseWidth} ${height}`;
} else {
const width = baseWidth * (defaultAspect / targetAspect);
const x = (baseWidth - width) / 2;
return `${x} 0 ${width} ${baseHeight}`;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment