Skip to content

Instantly share code, notes, and snippets.

@sidisinsane
Created April 26, 2020 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidisinsane/bb058d77730dbe2b4921d7a383680b62 to your computer and use it in GitHub Desktop.
Save sidisinsane/bb058d77730dbe2b4921d7a383680b62 to your computer and use it in GitHub Desktop.
Calculates Dimensions and Ratio for an Object to fit in a Container
const getObjectFitData = (obj, container, cover=true) => {
let result = {};
const ratioX = container.width / obj.width;
const ratioY = container.height / obj.height;
const ratioFit = cover ? Math.max(ratioX, ratioY) : Math.min(ratioX, ratioY);
result.ratio = Math.ceil(ratioFit * 100) / 100;
result.width = Math.ceil(obj.width * result.ratio);
result.height = Math.ceil(obj.height * result.ratio);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment