(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 notified about future articles and stay in touch via email.

I write about Django, Kubernetes, Docker, automation- and deployment topics, but would also like to keep you up to date about news around the business-side of things.

Privacy and your data: You can get more information about the usage of your data, the storage of your registration, sending out mails with the US-provider ConvertKit, statistical analysis of emails sent and your possibility to unsubscribe in my Privacy Policy.

I use the US-provider ConvertKit for email automation. By clicking to submit this form, you acknowledge that the information you provide will be transferred to ConvertKit for processing in accordance with their Privacy Policy and Terms.

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