vsupalov


Centered canvas element in HTML5

October 29, 2011 [ canvas | html | old ]

If you want a fixed-sized canvas element on an otherwise blank page, the following markup and code might be interesting for you:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <style>
      body { background-color: black; }
      #cvs { background-color: white; }
    </style>
    <script>
      // the desired canvas dimensions
      var canvasWidth = 500;
      var canvasHeight = 500;

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

        // compute margins
        var marginLeft = (window.innerWidth-canvasWidth)/2;
        var marginTop = (window.innerHeight-canvasHeight)/2;

        // set canvas dimensions
        cvs.width = canvasWidth;
        cvs.height = canvasHeight;
        // set css properties
        cvs.style.marginLeft = marginLeft+"px";
        cvs.style.marginTop = marginTop+"px";
      }
    </script>
  </head>

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

The style in the code is only there to make the result instantly visible. If you want to make the canvas element recenter on a resize event, you just need to bind a function to the window.onresize event. However, if you want to resize the canvas elements dynamically, remember that the drawn content gets erased. See this snippet for a related example.

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, and zero spam!