Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas fit to window

Tags:

html

canvas

size

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.

like image 398
Larry Avatar asked Mar 20 '13 13:03

Larry


People also ask

How do I make my canvas fit the screen in HTML?

Set the Size with CSSto set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.

How do I resize a canvas to resize a window?

Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .

How do I fill the whole screen in canvas?

To make the HTML canvas full screen with JavaScript, we can set the canvas width and height to the browser window width and height respectively. We select the canvas with document. querySelector . Then we add the resize function that sets the canvas width and height to the window.

How do you resize a canvas?

With the Select and Move Tool, click the canvas size label or border to select the canvas. Click the canvas border handles to resize the canvas dynamically. When you drag the border handles without using any keyboard modifiers, the canvas resizes non-uniformly. Hold Shift to constrain the resize proportions.


2 Answers

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

like image 76
Loktar Avatar answered Oct 21 '22 23:10

Loktar


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

body {
    margin: 0;
    padding: 0;
}
canvas {
    display: block;
}
like image 39
Lonelydatum Avatar answered Oct 21 '22 23:10

Lonelydatum