Search code examples
htmlmobilecanvasfirefox-os

Make canvas occupy as much space as possible


I'm trying to make my HTML5 Canvas occupy as much space as possible. I'm making a game fore Firefox OS that uses the canvas and testing with the Firefox OS simulator.

By "as much space as possible", I mean the whole screen, without scrollbars.

Ideally, a cross-platform way (that also works on Android and iOS) is preferred.


Solution

  • You need to do a few things, set the the canvas position to absolute, and make sure there is no padding, or margins set in the containing element.

    The following is what I use in all of my canvas demos

    CSS

    body, html {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
        overflow: hidden;
    }
    canvas {
        position:absolute;
    }
    

    JavaScript

    var canvas = document.getElementById("canvas"),
        width = window.innerWidth,
        height = document.body.offsetHeight;
    
    window.onresize = function () {
        height = canvas.height = document.body.offsetHeight;
        width = canvas.width = document.body.offsetWidth;
    };
    

    Full Screen Demo