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.

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