6

I have an image that I would like to scale to full screen. How would I do this using JavaScript/jQuery? No animation is necessary, just resizing the image.

<img src="something.jpg" onload="scaleToFullScreen()" />
Andrew
  • 227,796
  • 193
  • 515
  • 708

3 Answers3

8

The only reliable solution is to use a formula to determine maximum scale ratio:

var $img = $('#content img'),
    imageWidth = $img[0].width, //need the raw width due to a jquery bug that affects chrome
    imageHeight = $img[0].height, //need the raw height due to a jquery bug that affects chrome
    maxWidth = $(window).width(),
    maxHeight = $(window).height(),
    widthRatio = maxWidth / imageWidth,
    heightRatio = maxHeight / imageHeight;

var ratio = widthRatio; //default to the width ratio until proven wrong

if (widthRatio * imageHeight > maxHeight) {
    ratio = heightRatio;
}

//now resize the image relative to the ratio
$img.attr('width', imageWidth * ratio)
    .attr('height', imageHeight * ratio);

//and center the image vertically and horizontally
$img.css({
    margin: 'auto',
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0
});
Community
  • 1
  • 1
Andrew
  • 227,796
  • 193
  • 515
  • 708
1

If you have it outside of all elements you can just use css: <img src="something.jpg" style="width:100%; height:100%" onload="scaleToFullScreen()" />

if you do not:

<img name='myImage' src="something.jpg" onload="onResize()" />
<script>
window.onresize = onResize;

function onResize(e){
    var img = var img = document.images.myImage;
    if ( img.width > img.height )
        img.width = window.innerWidth
    else
        img.height = window.innerHeight;
}
</script>
locrizak
  • 12,192
  • 12
  • 60
  • 80
  • that would not be proportionate. I need to "scale" it, not skew it. – Andrew Nov 16 '11 at 20:15
  • @Andrew so if the window is not the same aspect ratio, should it [letterbox](http://en.wikipedia.org/wiki/Letterbox)? – Nicole Nov 16 '11 at 20:18
  • Updated. only changing the width will change the height proportionatly – locrizak Nov 16 '11 at 20:25
  • 1
    I don't think this will work if the image is taller than it is wide. – Andrew Nov 16 '11 at 20:28
  • true, try that. It would be something so that effect – locrizak Nov 16 '11 at 20:31
  • @locrizak actually, it does not work when the browser window is short. – Andrew Nov 16 '11 at 21:17
  • @locrizak The if statement defaults to the dimensions of the image, not the current window size. So the image will scale to full width, but the browser is too short to display it all, so the rest gets cut off when it should have scaled to full height. – Andrew Nov 16 '11 at 21:22
0

You can use viewerjs which is perfict library to able users to browse your images to view fullpage and fullscreen, slide them and view slide between them check this link : https://github.com/fengyuanchen/viewerjs

Khaled AbuShqear
  • 1,230
  • 14
  • 24