javascripthtmlhtml5-canvas

Resize HTML5 canvas to fit window


How can I automatically scale the HTML5 <canvas> element to fit the page?

For example, I can get a <div> to scale by setting the height and width properties to 100%, but a <canvas> won't scale, will it?


Solution

  • I believe I have found an elegant solution to this:

    JavaScript

    /* important! for alignment, you should make things
     * relative to the canvas' current width/height.
     */
    function draw() {
      var ctx = (a canvas context);
      ctx.canvas.width  = window.innerWidth;
      ctx.canvas.height = window.innerHeight;
      //...drawing code...
    }
    

    CSS

    html, body {
      width:  100%;
      height: 100%;
      margin: 0;
    }
    

    Hasn't had any large negative performance impact for me, so far.