How to get height and width of viewport without creating scrollbars?

778 Views Asked by At

Trying to extend an HTML canvas across an entire page, but the jQuery width() and height() functions are creating vertical and horizontal scrollbars.

HTML

<body>
    <canvas id="bg_canvas" width="" height=""></canvas>
</body>

jQuery

// Expand canvas to full viewport size
    var vp_width = window.clientWidth;
    var vp_height = window.clientHeight;

    $("#bg_canvas").css({
        "width" : vp_width,
        "height" : vp_height
    });

// Canvas Drawing
    var canvas = document.getElementById("bg_canvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle="#cbf7ed";
    ctx.fillRect(100,100,vp_width,100);

Also tried the Javascript window.innerheight and window.innerWidth, but that also creates scrollbars.

1

There are 1 best solutions below

1
Pezzer On

The default browser stylesheet is likely giving the <body> element a margin. Because, the canvas is within the body, that would make the canvas larger than its parent, creating a scrollable view.

If you want the canvas to span the width of the window, remove margin and padding from the body element via CSS. You can verify this with inline styling: <body style="margin:0 padding:0"> (though its generally best practice to place styling in discrete files or at least in the html header).

Alternatively, if you want the canvas to span the body, use something like:

var vp_width = $('body').innerWidth;
var vp_height = $('body').innerHeight;