I have an existing site that requires a background image on the home page.
The following code works perfectly on the site, but I am unable to work out how to maintain the images aspect ratio.
function resize(itemToResize){
var newHeight = $(document).height() -120,
newWidth = $(window).width();
$(itemToResize).css({
"width" : newWidth,
"height" : newHeight
});
};
I think I need some sort of if statement such as if the width is the same as the window width and the height is too small match the height and adjust the width... I just can't work out the correct syntax!
Update: using the method described here Whats the algorithm to calculate aspect ratio? I need an output like: 4:3, 16:9 I can access the Aspect Ratio of the image. However, Now I have my ratio I don't know what to do with it!
Updated code:-
function gcd (a, b) {
return (b == 0) ? a : gcd (b, a%b);
}
function resize(itemToResize){
var newHeight = $(document).height() -120,
newWidth = $(window).width();
var w = $(itemToResize).width(),
h = $(itemToResize).height(),
r = gcd (w, h);
$(itemToResize).css({
"width" : newWidth,
"height" : newHeight
});
};
UPDATE 2:
After plugging away at this for a bit longer I have this code:
function resize(itemToResize){
var AspectRatio = $(itemToResize).width()/$(itemToResize).height();
var WindowHeight = $(document).height() -205;
var WindowWidth = $(window).width();
var AspectRatio = WindowWidth/WindowHeight;
if (AspectRatio >= AspectRatio) {
$(itemToResize).css({
"width" : WindowWidth,
"height" : WindowWidth/AspectRatio
});
$('body').css({
"height" : WindowWidth/AspectRatio
});
} else {
$(itemToResize).css({
"width" : WindowHeight*AspectRatio,
"height" : WindowHeight
});
$('body').css({
"height" : WindowHeight
});
};
};
Which maintains the aspect ration but doesn't quite stretch properly. So a fix but only partially.