11

I'm trying to get my canvas to fit the page, when i do:

ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

It goes just over horizontally and vertically which is adding scroll bars. the size its going over is about the size of the scroll bars are being accounted for before they're even there (just a guess) is this whats happening, how would I go about getting it to fit the page with no scrollbars.

Larry
  • 1,045
  • 4
  • 11
  • 18

4 Answers4

16

Set the the canvas position to absolute. Also make sure there is no padding, or margins set in the containing element.

This is what I use on all of my full screen canvas demos.

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

Full Screen Demo

Loktar
  • 32,547
  • 8
  • 83
  • 101
  • 1
    Love it. Thank You so much – DollarAkshay Feb 01 '17 at 14:25
  • `canvas { width: 100%; height: 100%; }` this works too, and it's always better not to use absolute positioning. (for example, if you use absolute positioning and the canvas is larger than the page then you cannot move up or down). – FedericoCapaldo May 19 '17 at 06:18
2

The canvas by default is set to display: inline-block. Change it to display: block

body {
    margin: 0;
    padding: 0;
}
canvas {
    display: block;
}
Lonelydatum
  • 758
  • 1
  • 11
  • 24
1

This worked for me

function resize() {

    var canvas = document.getElementById('game');
    var canvasRatio = canvas.height / canvas.width;
    var windowRatio = window.innerHeight / window.innerWidth;
    var width;
    var height;

    if (windowRatio < canvasRatio) {
        height = window.innerHeight;
        width = height / canvasRatio;
    } else {
        width = window.innerWidth;
        height = width * canvasRatio;
    }

    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
};

window.addEventListener('resize', resize, false);
Petr
  • 1,281
  • 10
  • 15
0

I had the same problem, and I solved it by removing the border.

Y-B Cause
  • 1,101
  • 12
  • 35