Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery resize to aspect ratio

How would I resize a image in jQuery to a consistent aspect ratio. For example setting maximum height and have the width resize correctly. Thanks.

like image 817
usertest Avatar asked Nov 05 '09 18:11

usertest


2 Answers

Here's a useful function that might do what you want:

jQuery.fn.fitToParent = function()
{
    this.each(function()
    {
        var width  = $(this).width();
        var height = $(this).height();
        var parentWidth  = $(this).parent().width();
        var parentHeight = $(this).parent().height();

        if(width/parentWidth < height/parentHeight) {
            newWidth  = parentWidth;
            newHeight = newWidth/width*height;
        }
        else {
            newHeight = parentHeight;
            newWidth  = newHeight/height*width;
        }
        var margin_top  = (parentHeight - newHeight) / 2;
        var margin_left = (parentWidth  - newWidth ) / 2;

        $(this).css({'margin-top' :margin_top  + 'px',
                     'margin-left':margin_left + 'px',
                     'height'     :newHeight   + 'px',
                     'width'      :newWidth    + 'px'});
    });
};

Basically, it grabs an element, centers it within the parent, then stretches it to fit such that none of the parent's background is visible, while maintaining the aspect ratio.

Then again, this might not be what you want to do.

like image 185
Eric Avatar answered Sep 29 '22 19:09

Eric


You could calculate this manually,

i.e.:

function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}

Make sure you use the ORIGINAL values for the image otherwise it will degrade over time.

EDIT: example jQuery version (not tested)

jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
    var aspectRatio = $(this).data('aspectRatio');
    if (aspectRatio == undefined) {
        aspectRatio = $(this).width() / $(this).height();
        $(this).data('aspectRatio', aspectRatio);
    }
    $(this).height(newHeight); 
    $(this).width(parseInt(newHeight * aspectRatio));
}
like image 45
Paul Avatar answered Sep 29 '22 19:09

Paul