Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  144] [ 2]  / answers: 1 / hits: 59450  / 15 Years ago, thu, november 5, 2009, 12:00:00

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.


More From » jquery

 Answers
87

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));
}

[#98379] Monday, November 2, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
averyc

Total Points: 102
Total Questions: 113
Total Answers: 89

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
;