Centered canvas element in HTML5

October 29, 2011

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">
    <meta charset="utf-8" />
      body { background-color: black; }
      #cvs { background-color: white; }
      // 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";

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

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?

Enter your email below to join my mailing list!