title: Relatively sizing HTML Canvas
body: <p>The HTML5 <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element"><code>&lt;canvas&gt;</code></a> element does not accept relative sizes (percent) for its <code>width</code> and <code>height</code> properties. </p>
  
  <p>What I'm trying to accomplish is to have my canvas sized relative to the window. This is what I've come up with so far, but I'm wondering if there is a better way that is:</p>
  
  <ol>
  <li>Simpler</li>
  <li>Does not require wrapping the <code>&lt;canvas&gt;</code> in a <code>&lt;div&gt;</code>. </li>
  <li>Not dependent on jQuery (I use it to get the width/height of the parent div)</li>
  <li>Ideally, doesn't redraw on browser resize (but I think that might be a requirement)</li>
  </ol>
  
  <p>See below for the code, which draws a circle in the middle of the screen, 40% wide up to a maximum of 400px. </p>
  
  <p>Live demo: <a href="http://jsbin.com/elosil/2">http://jsbin.com/elosil/2</a></p>
  
  <p>Code:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;Canvas of relative width&lt;/title&gt;
      &lt;style&gt;
          body { margin: 0; padding: 0; background-color: #ccc; }
          #relative { width: 40%; margin: 100px auto; height: 400px; border: solid 4px #999; background-color: White; }
      &lt;/style&gt;
      &lt;script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"&gt;&lt;/script&gt;
      &lt;script&gt;
          function draw() {
              // draw a circle in the center of the canvas
              var canvas = document.getElementById('canvas');
              var relative = document.getElementById('relative');
              canvas.width = $(relative).width();
              canvas.height = $(relative).height();
              var w = canvas.width;
              var h = canvas.height;
              var size = (w &gt; h) ? h : w; // set the radius of the circle to be the lesser of the width or height;
              var ctx = canvas.getContext('2d');
              ctx.beginPath();
              ctx.arc(w / 2, h / 2, size/2, 0, Math.PI * 2, false);
              ctx.closePath();
              ctx.fill();
          }
  
          $(function () {
              $(window).resize(draw);
          });
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body onload="draw()"&gt;
      &lt;div id="relative"&gt;
          &lt;canvas id="canvas"&gt;&lt;/canvas&gt;
      &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>