Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- params:
- image - DOM element
- div - parent div of image
- scaleMode - 'scale' or 'scaleCrop'
- */
- function centerImageInDiv(image, div, scaleMode){
- $(image).css({
- width : "auto",
- height : "auto"
- });
- if (!scaleMode) scaleMode = "scaleCrop";
- var containerWidth = $(div).width();
- var containerHeight = $(div).height();
- var imgWidth = image.width;
- var imgHeight = image.height;
- var newWidth, newHeight;
- if ((containerWidth / containerHeight < imgWidth / imgHeight) ^ (scaleMode != "scale")) {
- newWidth = Math.min(containerWidth, imgWidth);
- newHeight = ((imgHeight * Math.min(containerWidth, imgWidth)) / imgWidth) >> 0;
- }
- else {
- newHeight = Math.min(containerHeight, imgHeight);
- newWidth = ((imgWidth * Math.min(containerHeight, imgHeight)) / imgHeight) >> 0;
- }
- $(image).css({
- width : newWidth + "px",
- height : newHeight + "px",
- "margin-left" : ((containerWidth - newWidth) >> 1) + "px",
- "margin-top" : ((containerHeight - newHeight) >> 1) + "px"
- });
- }
- // usage:
- image.on('load', function(){
- centerImageInDiv(this, $(this).parent()[0], "scale");
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement