title: Javascript: Variable-sized image in fixed-sized canvas
body: <p>I have a fixed HTML5 canvas with dimensions 300x300. I'm resizing other images on the page to have maximum widths/heights of 300px (depending on which dimension is larger) via Javascript.</p>
  
  <p>This doesn't actually resize the source images, though, and when I draw them on the canvas, the original size is used.</p>
  
  <p>Is there a way to:</p>
  
  <ol>
  <li>Resize these images with Javascript so that they're drawn to the canvas with a maximum height or width of 300px.</li>
  </ol>
  
  <p>AND</p>
  
  <ol start="2">
  <li>Have the canvas retain its 300x300 dimensions with the resized image inside of it, so that a 300x300 square with the variable-sized image completely contained inside of it is created?</li>
  </ol>
  
  <p>(Think making a 300x300 Photoshop file where you drop in various images and they resize to fit)</p>
  
  <p>Is this even possible with Javascript/canvas?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Here is the code I ended up using based on the accepted answer:</p>
  
  <pre><code>var ssItems = [exampleUrls], //array of image paths
  imgHolder = document.getElementById("img-holder");
  
  for (var i = 0; i &lt; ssItems.length; i++) {
            var img = new Image(),
              imgSrc = "/ItemImages/Large/" + ssItems[i] + ".jpg",
              imgW,
              imgH;
            img.src = imgSrc;
            img.onload = function () {
                var canvas = document.createElement("canvas"),
                  ctx = canvas.getContext("2d");
                canvas.setAttribute("class", "img-canvas");
                canvas.setAttribute("width", "300");
                canvas.setAttribute("height", "300");
                imgHolder.appendChild(canvas);
                imgW = (canvas.height * this.width) / this.height;
                imgH = (canvas.width * this.height) / this.width;
                if (this.height &gt; this.width) {
                  ctx.drawImage(this, canvas.width / 2 - imgW / 2, 0, imgW, canvas.height);
                } else {
                  ctx.drawImage(this, 0, canvas.height / 2 - imgH / 2, canvas.width, imgH);
                }
              }
  </code></pre>