Created
November 5, 2012 21:10
-
-
Save bdalziel/4020359 to your computer and use it in GitHub Desktop.
JS to scale img to browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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