Dynamic Image Resizing - javascript

I have an image on a webpage that needs to be stretched to fit the available space in the window whilst maintaining its proportion. Here's what I've got:
http://www.lammypictures.com/test/
I would like the large image to proportionally stretch to match the height and widths of the browser, minus the size of the divs to the left and bottom.
So the problem is 2 fold really; first i need to get the max height and width minus the link and image bars, secondly i need to resize the image on a browser resize whilst maintaining proportions.
Any help would be much appreciated.
Cheers
CIP

You could try using jQuery ui scaling effect:
$(document).ready(function () {
resizeImage(); // initialize
$(window).resize(function () {
resizeImage(); // initialize again when the window changes
});
function resizeImage() {
var windowHeight = $(window).height() - $('#nav').height(),
windowWidth = $(window).width(),
percentage = 0;
if (windowHeight >= windowWidth) {
percentage = (windowWidth / $('#image').width() ) * 100;
}
else {
percentage = ( windowHeight / $('#image').height() ) * 100;
}
$('#image').effect('scale', { percent : percentage }, 1);
};
});
Tested and works great, however, a few tweaks maybe needed to get it just the way you like it.

You may just not setup the image element width and height attributes, and write next styles:
.hentry img { max-width: 100%; }
And it will shrink relative to the minimum side.
P.S. But not in position: absolute; block which not have any size. Set up the parent block to relative positioning.

Related

Proportionally scale website to fit browser window

What would be an elegant solution to proportionally scale and center an entire website to fit a browser window (and updating as it's re-sized)
Assume the base layout is 720x500px
Content should proportionally scale to fit, and then re-center.
Essentially, operating like this Flash plugin: http://site-old.greensock.com/autofitarea/ (though base size is known)
Site will contain several different types of elements in that 720x500 area... ideal solution would just scale the whole thing, not needing to style each individual element (in case it matters- images will be SVG and so scaling should have no negative affect on resolution)
Depending on the browsers you need to support (IE9+), you could achieve that with simple CSS transform.
See an example (using jQuery) in this jsfiddle
var $win = $(window);
var $lay = $('#layout');
var baseSize = {
w: 720,
h: 500
}
function updateScale() {
var ww = $win.width();
var wh = $win.height();
var newScale = 1;
// compare ratios
if(ww/wh < baseSize.w/baseSize.h) { // tall ratio
newScale = ww / baseSize.w;
} else { // wide ratio
newScale = wh / baseSize.h;
}
$lay.css('transform', 'scale(' + newScale + ',' + newScale + ')');
console.log(newScale);
}
$(window).resize(updateScale);
If you need backwards compatibility, you could size everything in your site with % or em, and use a similar javascript to control the scale. I think that would be very laborious though.
One solution I'm using is working with a container in which I put an iframe that's being resized to fit as much available screen as possible without losing it's ratio. It works well but it's not completely flexible: you need to set dimensions in your content page in % if you want it to work. But if you can manage your page this way, I think it does pretty much what you want.
It goes like this. You create a container html page that's basically only styles, the resize script and the iframe call. And you content goes into the iframe page.
<style>
html, body
{
border: 0px;margin: 0px;
padding:0px;
}
iframe
{
display: block;
border: 0px;
margin: 0px auto;
padding:0px;
}
</style>
<script>
$(document).ready(function(e){
onResizeFn();
});
$(window).resize(function(e){
onResizeFn();
});
// this stretches the content iframe always either to max height or max width
function onResizeFn(){
var screen_ratio = 0.70 // this is your 720x500 ratio
if((window.innerHeight/window.innerWidth) > screen_ratio){
var theWidth = window.innerWidth
var theHeight = (window.innerWidth*screen_ratio);
} else {
var theHeight = window.innerHeight;
var theWidth = (window.innerHeight/screen_ratio);
}
document.getElementById("your_iframe").width = theWidth + "px"
document.getElementById("your_iframe").height = theHeight + "px"
}
</script>
// And then you call your page here
<iframe id='your_iframe' src='your_content_page' scrolling='no' frameborder='0'"></iframe>

Changing the background image according to resolution - javascript only

there's a lot of this question scattered over stackoverflow, but I can't seem to find an answer that specifically suits my situation.
I have made a background in HD 1920x1080 for a school project I'm making, and I'm trying to make it fit for every resolution there is. So what I did was resizing this image for every specific resolution, putting me in an awkward spot to code it, as I cannot use jQuery, I'm not allowed to.
I'm thinking of using the screen.width property, but I'd need a length too as I have multiple backgrounds with the ...x768 resoulution.
Is there anyone who'd be able to tell me how to change my body's background, depending on the user's height and width of the screen?
Thank you very much,
Michiel
You can use window.innerWidth and window.innerHeight to get the current dimensions of your browser's window.
Which means that if your browser takes half of your 1920x1080 desktop, it'll compute to something like:
window.innerWidth ~= 540
window.innerHeight ~= 1920 // actually something smaller because it doesn't count your browser's chrome
Your window can of course change size, and if you want to handle that, you can listen to the event "resize" for your window:
window.addEventListener('resize', function () {
// change background
});
To change the body's background without jQuery, you can do something like this:
document.body.style.backgroundImage = "url(/* url to your image...*/)";
To recap:
// when the window changes size
window.addEventListener('resize', function () {
var windowWidth = window.innerWidth; // get the new window width
var windowHeight = window.innerHeight; // get the new window height
// use windowWidth and windowHeight here to decide what image to put as a background image
var backgroundImageUrl = ...;
// set the new background image
document.body.style.backgroundImage = "url(" + backgroundImageUrl + ")";
});
I am not sure what browsers you are supposed to be compatible with. This should work in all latest versions of the big browsers.
You may check the window width and change the background depending on the results.
var width = window.innerWidth;
var height = window.innerHeight;
var body = document.body;
if (width <= 1600 && height <= 1000) {
body.style.background = "url(path/to/1600x1000.jpg)";
}
if (width <= 1400 && height <= 900) {
body.style.background = "url(path/to/1400x900.jpg)";
}
// continue as desired
http://jsbin.com/wosaduho/1/
Even better, use some media queries to reduce javascript required.
#media screen and (max-width: 1600px) {
.element {
background: url(path/to/1600x1000.jpg);
}
}
#media screen and (max-width: 1400px) {
.element {
background: url(path/to/1400x900.jpg);
}
}
body {
background-image: url(images/background.jpg);
background-size:cover;/*If you put "contain" it will preserve its intrinsic aspect ratio*/ background-repeat: no-repeat;
}
Try this
You might want to trigger a function like the following on window load and/or on window resize:
function SwapImage(){
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
el = document.getElementById('change-my-background');
// use conditionals to decide which image to show
if(w < 1200 && h < 800){
el.style.backgroundImage = "url('img_1200x800.png')";
}
if(w < 900 && h < 600){
el.style.backgroundImage = "url('img_900x600.png')";
}
// etc...
}

jQuery - resizing image to fit div [duplicate]

This question already has answers here:
Resize an image to fit in div
(5 answers)
Closed 9 years ago.
I have divs varying in height and width and wish for my images to be automatically resized to fill these divs 100%, and then of course centred.
At the moment my images are set to width 100% and then using the jQuery below centred, but this only works for images where the height are more than the div once resized.. how would I make it 100% for both height and width and center also.. completely filling the div (even if this means stretching the image)!
Thanks.
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var top_margin = -(img_height / 2);
$(item).css({
'top': '50%',
'margin-top': top_margin
});
});
Use CSS to set both the Width and Height of the image to 100% and the image will be automatically stretched to fill the containing div, without the need for jquery.
Also, you will not need to center the image as it will already be stretched to fill the div (centered with zero margins).
HTML:
<div id="containingDiv">
<img src="">
</div>
CSS:
#containingDiv{
width: 200px;
height: 100px;
}
#containingDiv img{
width: 100%;
height: 100%;
}
That way, if your users have javascript disabled, the image will still be stretched to fill the entire div width/height.
OR
The JQuery way (SHRINK/STRETCH TO FIT - INCLUDES WHITESPACE):
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//IMAGE IS SHORTER THAN CONTAINER HEIGHT - CENTER IT VERTICALLY
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin });
}else if(img_height>div_height){
//IMAGE IS GREATER THAN CONTAINER HEIGHT - REDUCE HEIGHT TO CONTAINER MAX - SET WIDTH TO AUTO
$(item).css({'width': 'auto', 'height': '100%'});
//CENTER IT HORIZONTALLY
var img_width = $(item).width();
var div_width = $(item).parent().width();
var newMargin = (div_width-img_width)/2+'px';
$(item).css({'margin-left': newMargin});
}
});
The JQuery way - CROP TO FIT (NO WHITESPACE):
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//INCREASE HEIGHT OF IMAGE TO MATCH CONTAINER
$(item).css({'width': 'auto', 'height': div_height });
//GET THE NEW WIDTH AFTER RESIZE
var img_width = $(item).width();
//GET THE PARENT WIDTH
var div_width = $(item).parent().width();
//GET THE NEW HORIZONTAL MARGIN
var newMargin = (div_width-img_width)/2+'px';
//SET THE NEW HORIZONTAL MARGIN (EXCESS IMAGE WIDTH IS CROPPED)
$(item).css({'margin-left': newMargin });
}else{
//CENTER IT VERTICALLY (EXCESS IMAGE HEIGHT IS CROPPED)
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin});
}
});
If you want to keep the image ratio, I would set max-height and max-width to 100%. Here's a sample to show how that works. That will effectively shrink images that are larger than the div, but it will keep the aspect ratio.
For images that are smaller than the div, you will have to scale up with JavaScript. The basic algorithm is like so:
Find the aspect ratio of the image (width / height)
Find the aspect ratio of the div (width / height)
If the image's aspect ratio is less than the div's, set the image's height to 100%
If the image's aspect ratio is greater than the div's, set the image's width to 100%
Whichever dimension is not set, set it to auto
Obviously, you could use this algorithm for scaling up or down, but if you can be guaranteed that your div will always be smaller than your image, you can use the simpler CSS solution.
It looks like you've got code to do centering, so I'll leave that to you.

element.height returns visible height - I want total?

So apparently this is only happening to me - and I can't think why but if it works, I'm happy :)
I have a full screen slideshow and I have created a function that will vertically center any images that are too large.
function fixImages(){
maxheight = $('.index-slide-container').height();
$('.index-slide-container img').each( function(index, ele){
if (ele.height > maxheight){
offset = ( maxheight - ele.height ) / 2;
$(ele).css('top', offset + 'px');
}
});
}
fixImages();
However, ele.height returns the height of the visible part of the image (the height of it's container, as it has overflow:hidden, even though when I console.log(ele) and expand the element, 'height' is clearly the correct value.
I have also tried $(ele).height(), $(ele).css('height'), $(ele).outerHeight() and ele.clientHeight; all of which return the same.
Thanks
I made some tests, and $('img').height(); is giving me the right height of the picture.
If you wish to center the picture vertically why don't you use the absolute positioning with css like this for example :
.index-slide-container img {
position:absolute;
top:50%;
}
And than, you could set the negative margin programmatically with jQuery :
$('.index-slide-container img').each( function(i, e){
var height = $(e).height() / 2;
$(e).css({'margin-top':'-'+height});
});

Render images at a standard size without stretching, with a minimum size

I need to render profile images in a grid of exactly 101x155 each.
Some images are too small, some too big, most are not the right aspect ratio.
How do I show the img with a minimum width and height, no distortion, and show the exact size I want?
Without actually modifying the images, you have a few options available to you.
img { max-width: 101px max-height: 155px }
this will make sure that the images don't go above the 101x155px wide. Because they aren't the perfect aspect ratio there still will be whitespace on the sides of the image if the aspect ratio isn't perfect.
Another way would be to encase them in a container
<div><img .../></div>
div {width: 101px; height: 155px; overflow: hidden}
img {width: 101px;} /*or do height: 155px)*/
This isn't perfect but it gives you a different result. This will require the images to be either taller or wider for all images.
The best way would be to resize, but I know we can't always have our way :)
How about some jQuery? If you just include the <img> with class="grid-img":
$(".grid-img").each(function(i){
var width = $(this).width();
var height = $(this).height();
var ar = height/width;
if(width > 101) {
var newWidth = 101;
var newHeight = 101 * ar;
} else {
var newHeight = 155;
var newWidth = ar / newHeight;
}
$(this).height(newHeight);
$(this).width(newWidth);
});
what this should do is: if the image's width is too big, resize it based on the width (maintaining aspect ratio). if not, resize it based on height (again maintaining AR).

Categories

Resources