Search code examples
javascripthtmlfullscreen

How to fill the browser window with a canvas element without creating scroll bars?


I have a problem to get my window size, I try this code:

Javascript

var game;
function game() {
    this.canvas = document.getElementById('canvas');
    this.canvasWidth = window.innerWidth;
    this.canvasHeight = window.innerHeight;    
    this.initCanvas = function() {
        this.canvas.style.width = this.canvasWidth + "px";
        this.canvas.style.height = this.canvasHeight + "px";
    }
    this.run = function() {
        this.initCanvas();
    }
}
game = new game();
game.run();

I also have

CSS

html, body {
    padding: 0;
    margin: 0;
}

I only have a canvas in my body.

Problem is, that I have a vertical and horizontal scroll bar. This means the size of canvas is too large. How to make it of the window size without the scroll bars appearing?


Solution

  • It looks like you're just trying to make your canvas have a width and height of 100%. You can do this with just css:

    HTML

    <body>
        <canvas id="canvas"></canvas>
    </body>
    

    CSS

    body, html {
        height: 100%;
        width: 100%;
        margin: 0px;
    }
    canvas {
        background: #ffcccc;
        height: 100%;
        width: 100%;
        display: block;
    }
    ​
    

    Demo

    Or if you want to use your code but get rid of the scroll bars on the window, you need to specify block on the canvas tag.

    CSS

    canvas {
        display: block;
    }
    

    Demo