Make HTML5 Canvas fill the whole page

To make an HTML5 canvas fill the entire browser viewport, you need to remove default margins/padding and set the canvas dimensions to 100% of the page.

CSS Setup

First, reset the default browser styles and set up the HTML structure:

* {
    margin: 0;
    padding: 0;
}
body, html {
    height: 100%;
    overflow: hidden; /* Prevents scrollbars */
}
#canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
}

Complete HTML Example

<!DOCTYPE html>
<html>
<head>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        body, html {
            height: 100%;
            overflow: hidden;
        }
        #canvas {
            position: absolute;
            width: 100%;
            height: 100%;
            display: block;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    
    <script>
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        
        // Set canvas resolution to match display size
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        // Draw a test rectangle
        ctx.fillStyle = '#4CAF50';
        ctx.fillRect(50, 50, 200, 100);
        
        ctx.fillStyle = 'white';
        ctx.font = '20px Arial';
        ctx.fillText('Full Screen Canvas', 60, 110);
    </script>
</body>
</html>

Handling Window Resize

To maintain full-page coverage when the browser window is resized:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    
    // Redraw content after resize
    ctx.fillStyle = '#2196F3';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.fillStyle = 'white';
    ctx.font = '24px Arial';
    ctx.fillText('Resized: ' + canvas.width + 'x' + canvas.height, 20, 40);
}

// Initial setup
resizeCanvas();

// Handle window resize
window.addEventListener('resize', resizeCanvas);

Key Points

  • CSS Reset: Remove default margins and padding with * { margin: 0; padding: 0; }
  • Canvas Sizing: Set both CSS dimensions (100%) and canvas resolution (innerWidth/innerHeight)
  • Position: Use position: absolute to remove the canvas from document flow
  • Overflow: Add overflow: hidden to prevent scrollbars
  • Resize Handling: Listen for window resize events to maintain full coverage

Conclusion

Making a canvas fill the entire page requires CSS reset, absolute positioning, and proper dimension handling. Always update both CSS size and canvas resolution for crisp rendering across different screen sizes.

Updated on: 2026-03-15T23:18:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements