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:
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()
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 ;)
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With