Skip to content

Instantly share code, notes, and snippets.

@Shilo
Last active August 21, 2018 04:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shilo/760e342e99451210594d18e604618fcb to your computer and use it in GitHub Desktop.
Save Shilo/760e342e99451210594d18e604618fcb to your computer and use it in GitHub Desktop.
Javascript snippet to aspect fit bounds in bounds.
aspectFitBoundsInBounds(src, dest, center=true) {
let WIDTH_KEY = "width";
let HEIGHT_KEY = "height";
let largerSide = src.height > src.width ? HEIGHT_KEY : WIDTH_KEY;
let smallerSide = largerSide == HEIGHT_KEY ? WIDTH_KEY : HEIGHT_KEY;
let aspectRatio = src[smallerSide]/src[largerSide];
src[largerSide] = dest[largerSide];
src[smallerSide] = dest[largerSide]*aspectRatio;
src.x = dest.x;
src.y = dest.y;
if (center) {
src.x += (dest.width-src.width)/2;
src.y += (dest.height-src.height)/2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment