Skip to content

Instantly share code, notes, and snippets.

@JCThePants
Last active December 5, 2015 03:46
Show Gist options
  • Save JCThePants/2081b8b72f4867c78616 to your computer and use it in GitHub Desktop.
Save JCThePants/2081b8b72f4867c78616 to your computer and use it in GitHub Desktop.
Fit an image inside a container (centered) while maintaining its aspect ratio
var slotWidth = 100; // The width of the container
var slotHeight = 100;// The height of the container
var imgWidth = 200; // The width of the image to draw inside the container
var imgHeight = 200; // The height of the image to draw inside the container
var offsetTop = 0; // The offset of the image from the top of the container
var offsetLeft = 0; // The offset of the image from the left of the container
var width = imgWidth; // the new image draw width
var height = imgHeight; // the new image draw height
if (imgWidth > slotWidth || imgHeight > slotHeight) {
// get ratio of image width to height and make the image the same width as the container
var ratio = imgHeight / imgWidth;
width = slotWidth;
height = slotWidth * ratio; // maintain aspect ratio
// make sure the new size isn't taller than the container
if (height > slotHeight) {
// make the image the same height as the container
ratio = imgWidth / imgHeight;
width = slotHeight * ratio; // maintain aspect ratio
height = slotHeight;
}
}
// center image
offsetLeft = (slotWidth - width) / 2;
offsetTop = (slotHeight - height) / 2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment