Skip to content

Instantly share code, notes, and snippets.

@mocon
Last active October 18, 2015 03:22
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 mocon/325b617d5597d9b367c7 to your computer and use it in GitHub Desktop.
Save mocon/325b617d5597d9b367c7 to your computer and use it in GitHub Desktop.
Fit an image of any dimensions into the space of an existing image. For example, when injecting into a Bootstrap grid. Example: http://myles.la/grid/
(function adjustImages(){
/* variables */
var wrapper = document.getElementsByClassName('wrapper')[0],
image = document.getElementsByClassName('variable-image')[0],
hiddenDiv = document.getElementsByClassName('hidden-div')[0],
neededWidth = 450,
neededHeight = 300,
neededRatio = neededHeight / neededWidth,
newImgRatio,
scaleRatio,
timer,
new_img = new Image();
/* determine provided image size and orientation */
new_img.onload = function() {
var img_width = 0,
img_height = 0;
img_width = this.width,
img_height = this.height,
newImgRatio = img_height / img_width;
if (newImgRatio < neededRatio){ /* landscape */
image.style.width = neededWidth + 'px';
image.style.height = 'auto';
image.style.marginTop = (neededHeight - image.height) / 2 + 'px';
image.style.marginLeft = 0 + 'px';
} else { /* portrait */
image.style.width = 'auto';
image.style.height = neededHeight + 'px';
image.style.marginTop = 0 + 'px';
image.style.marginLeft = (neededWidth - image.width) / 2 + 'px';
}
}
new_img.src = image.src;
/* adjust wrapper div dimensions */
wrapper.style.width = neededWidth + 'px';
wrapper.style.height = neededHeight + 'px';
wrapper.style.backgroundImage = 'url("' + image.src + '")';
/* transform all divs to calculated client width */
scaleRatio = hiddenDiv.clientWidth / neededWidth;
wrapper.style.transform = 'scale(' + scaleRatio + ')';
/* adjust bottom margin to account for 3d transform's change in element height */
wrapper.style.marginBottom = -(neededHeight - (neededHeight * scaleRatio)) + 'px';
/* crop again on window resize */
window.onresize = function(){
clearTimeout(timer);
timer = setTimeout(adjustImages(), 500);
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment