Skip to content

Instantly share code, notes, and snippets.

@bdalziel
Created November 5, 2012 21:10
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 bdalziel/4020359 to your computer and use it in GitHub Desktop.
Save bdalziel/4020359 to your computer and use it in GitHub Desktop.
JS to scale img to browser
var sizeSlideAsset = function (slideNode) {
var img = slideNode.one('.assetWrap img');
var assetWrap = img.ancestor('.assetWrap');
var wrapWidth = assetWrap.get('offsetWidth');
var wrapHeight = assetWrap.get('offsetHeight');
var imgWidth = Y.Util.getClassValue(img, 'imgW');
var imgHeight = Y.Util.getClassValue(img, 'imgH');
var targetDimensions = getImageDimensionsToFitContainer(imgWidth, imgHeight, wrapWidth, wrapHeight);
img.setStyles({
'width': targetDimensions.width + 'px',
'height': targetDimensions.height + 'px'
});
}
var getImageDimensionsToFitContainer = function (imgWidth, imgHeight, wrapWidth, wrapHeight) {
var targetImgHeight = imgHeight;
var targetImgWidth = imgWidth;
var verticalScalingFactor = (wrapHeight/imgHeight);
// Scale
if ((imgWidth*verticalScalingFactor) <= wrapWidth) {
// Height is the limiting dimension
targetImgWidth = Math.round(imgWidth * verticalScalingFactor);
targetImgHeight = wrapHeight;
Y.log("Fitting vertically, scale=" + verticalScalingFactor + ". W=" + targetImgWidth + " H=" + targetImgHeight);
}
else if ((imgWidth*verticalScalingFactor) > wrapWidth) {
var horizontalScalingFactor = (wrapWidth/imgWidth);
// Width is the limiting dimension
targetImgWidth = wrapWidth;
targetImgHeight = Math.round(imgHeight * horizontalScalingFactor);
Y.log("Fitting horizontally, scale=" + horizontalScalingFactor + ". W=" + targetImgWidth + " H=" + targetImgHeight);
}
return {
width: targetImgWidth,
height: targetImgHeight
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment