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()" />
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With