(Almost fullscreen) page filling canvas element in HTML

October 29, 2011

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">
    <meta charset="utf-8" />
      body, html {
        background-color: black;
        width: 100%;
        margin: 0px;
      #cvs { background-color: white; }
      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);

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

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.

Join the Mailing List

Subscribe to get weekly updates and my latest articles by email.

    (About the content, privacy, analytics and revocation).

    We won't send you spam. Unsubscribe at any time.

    Powered By ConvertKit