title: HTML - display an image as large as possible while preserving aspect ratio
body: <p>I'd like to have an HTML page which displays a single PNG or JPEG image. I want the image to take up the whole screen but when I do this:</p>
  <pre><code>&lt;img src=&quot;whatever.jpeg&quot; width=&quot;100%&quot; height=&quot;100%&quot; /&gt;
  </code></pre>
  <p>It just stretches the image and messes up the aspect ratio. How do I solve this so the image has the correct aspect ratio while scaling to the maximum size possible ?</p>
  <hr />
  <p>The solution posted by Wayne <strong>almost</strong> works except for the case where you have a tall image and a wide window. This code is a slight modification of his code which does what I want:</p>
  <pre class="lang-html prettyprint-override"><code>&lt;html&gt;
    &lt;head&gt;
      &lt;script&gt;
        function resizeToMax(id){
            myImage = new Image() 
            var img = document.getElementById(id);
            myImage.src = img.src; 
            if(myImage.width / document.body.clientWidth &gt; myImage.height / document.body.clientHeight){
                img.style.width = &quot;100%&quot;;
            } else {
                img.style.height = &quot;100%&quot;;
            }
        }
      &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;img id=&quot;image&quot; src=&quot;test.gif&quot; onload=&quot;resizeToMax(this.id)&quot;&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>