HTML - display an image as large as possible while preserving aspect ratio

You don't necessarily want to stretch in a certain direction based on which is bigger. For example, I have a widescreen monitor, so even if it's a wider image than it is tall, stretching it left-to-right may still clip the top and bottom edges off.

You need to calculate the ratio between the window width and height and the image width and height. The smaller one is your controlling axis - the other is dependent. This is true even if both axes are larger than the respective window length.

<script type="text/javascript">
// <![CDATA[
function resizeToMax (id) {
    var img = document.getElementById(id);
    myImage = new Image();
    myImage.src = img.src;
    if (window.innerWidth / myImage.width < window.innerHeight / myImage.height) {
        img.style.width = "100%";
    } else {
        img.style.height = "100%";
    }
}
// ]]>
</script>

Here's a quick function that will adjust the height or width to 100% depending on which is bigger. Tested in FF3, IE7 & Chrome

<html>
<head>
<script>
function resizeToMax(id){
    myImage = new Image() 
    var img = document.getElementById(id);
    myImage.src = img.src; 
    if(myImage.width > myImage.height){
        img.style.width = "100%";
    } else {
        img.style.height = "100%";
    }
}
</script>
</head>
<body>
<img id="image" src="test.gif" onload="resizeToMax(this.id)">
</body>
</html>

Tags:

Html