vsupalov

(Almost fullscreen) page filling canvas element in HTML

October 29, 2011 [ canvas | html | old ]

The following snippet realizes a dynamically sized (almost) page filling canvas element on an otherwise blank HTML page. There is a 5 pixel margin on each side of the canvas, so it is basically just big and centered. The reason for this is that, unfortunately simply setting the respective canvas dimensions to window.innerHeight and window.innerWidth results in unnecessary, ugly scrollbars in Chrome and Firefox (but only if <!DOCTYPE html> is used). I would really like to see a truly page filling variant in valid HTML5.

Note: resizing a canvas element erases its content.

PS: A true fullscreen canvas, without silly margins, can be achieved by setting the overflow: hidden css rule for body.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <style>
      body, html {
        background-color: black;
        width: 100%;
        margin: 0px;
      }
      #cvs { background-color: white; }
    </style>
    <script>
      var cvs;
      var margin = 5;

      function init() {
        cvs = document.getElementById("cvs");

        doResize(); // set initial size
        window.onresize = doResize; // bind event listener
      }

      function doResize() {
      // css margins to create something like a frame around the element
      // and prevent browsers from making scrollbars visible
      cvs.style.marginLeft = margin+"px";
      cvs.style.marginTop = margin+"px";

      // set canvas dimensions
      cvs.width = window.innerWidth-(margin*2);
      cvs.height = window.innerHeight-(margin*2);
    }
  </script>
  </head>

  <body onload="init();">
    <canvas id="cvs"><canvas>
  </body>
</html>

Setting the width and margin of the body and html elements is necessary to guarantee the desired effect, the rest of the css markup is just there to make the result instantly visible.

Want to be notified when I publish new content?

Just enter your name and email below. You will also get content that I share exclusively with the list. Zero spam!