Creating a responsive full page canvas

suggest change

Starter code to create and remove a full page canvas that responds to resize events via javascript.

var canvas;    // Global canvas reference
var ctx;       // Global 2D context reference
// Creates a canvas
function createCanvas () {                
    const canvas = document.createElement("canvas"); = "absolute"; // Set the style     = "0px";      // Position in top left      = "0px";   = 1;        
    document.body.appendChild(canvas);  // Add to document
    return canvas;
// Resizes canvas. Will create a canvas if it does not exist
function sizeCanvas () {                
    if (canvas === undefined) {         // Check for global canvas reference
        canvas = createCanvas();        // Create a new canvas element
        ctx = canvas.getContext("2d");  // Get the 2D context
    canvas.width  = innerWidth;         // Set the canvas resolution to fill the page
    canvas.height = innerHeight;        
// Removes the canvas
function removeCanvas () {
    if (canvas !== undefined) {              // Make sure there is something to remove
        removeEventListener("resize", sizeCanvas); // Remove resize event
        document.body.removeChild(canvas);   // Remove the canvas from the DOM
        ctx = undefined;                     // Dereference the context
        canvas = undefined;                  // Dereference the canvas

// Add the resize listener
addEventListener("resize", sizeCanvas); 
// Call sizeCanvas to create and set the canvas resolution
// ctx and canvas are now available for use.

If you no longer need the canvas you can remove it by calling removeCanvas()

A demo of this example at jsfiddle

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents