Iaiao
Iaiao

Reputation: 13

How to set width and height of canvas to all height and width of browser without overflow?

I want to make a canvas with width and height of document without scrolls, but I don't know how to do this. I tried:

canvas.width = window.innerWidth;
canvas.width = parseInt(getComputedStyle( document.body ).getPropertyValue( 'width' ));
canvas.width = document.body.offsetWidth
canvas.width = document.body.clientWidth

But I got 1-20 unused pixels that I can scroll, also I can't reduce width and height by fixed number of pixels - different browsers show it differently.

Upvotes: 0

Views: 72

Answers (3)

Iaiao
Iaiao

Reputation: 13

Fixed by "display: block", canvas elements aren't blocks by default.

Upvotes: 1

tonyofthewoods
tonyofthewoods

Reputation: 120

window.innerWidth gives you the whole width inside the window frame ignoring the scroll bars.

document.body.clientWidth gives you the width inside the vertical scroll bar - if present.

These both work on current versions of Safari and Chrome - I just gave them a quick try.

Both should work on all modern browsers check here for window.innerWidth and here for document.body.clientWidth.

I'd be interested to know any circumstances where these don't work as advertised.

(Of course if you executed the code exactly as you've shown it you would end up with just the value of document.body.clientWidth. I'm guessing you meant you tried each of them in turn.)

Upvotes: 0

jtylerm
jtylerm

Reputation: 472

if you're asking how to make an element 100% of the viewport's width and height, you can use CSS...

#selector_id {
    width: 100vw,
    height: 100vh
}

Upvotes: 0

Related Questions