Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using window.innerWidth and window.innerHeight makes scrollbars appear

I'm trying to make a simple canvas that stretches itself to fully fill the viewport, but I don't want scrollbars to appear, a thing that happens if I try to resize the canvas in JS using window.innerWidth and window.innerHeight.

Note: I don't want to resize the canvas in CSS because the elements inside get all stretched out since from what I've understood the CSS treats the canvas as an img, and doesn't actually stretch the resolution of the canvas.

This is what happens: enter image description here This is the code: css:

    html,
body {
    height: 100%;
    width: 100%;
    margin:0;
    padding:0;
}

/*canvas*/
#bg {
    background: #171629;
}

js:

ctx.beginPath()
ctx.canvas.width  =  window.innerWidth
ctx.canvas.height = window.innerHeight


ctx.rect(20, 40, 50, 50)
ctx.fillStyle = "#e5e5e5"
ctx.fill()
ctx.closePath()
like image 318
iLikeKFC Avatar asked Jul 27 '26 15:07

iLikeKFC


2 Answers

This is an old question but still doesn't have any correct answer, so I will post my answer here for anyone looking for a solution.

If you want to get rid of the scrollbars when setting canvas width/height to the window's width/height just display canvas as block:

  * { 
    margin:0; 
    padding:0; 
  }
  canvas {  
    display: block;  /* <---- As simple as that */
  }

You're welcome ;)

like image 102
medBouzid Avatar answered Jul 29 '26 04:07

medBouzid


After a bunch of trying I found this as a solution:

css:

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

js:

canvasElement.height = window.innerHeight;
canvasElement.width = document.body.clientWidth;
like image 38
PolyGlot Avatar answered Jul 29 '26 06:07

PolyGlot