Ask coding questions

← Back to all posts
How to make a canvas full screen in HTML, CSS, JS
Dunce (65)

When trying to make a canvas full screen you might think you could just write a CSS rule to resize it, like so:

canvas {
width: 100%;
height 100vh;
}

but then the contents of the canvas are left blurry and stretched. Okay then you can just resize the canvas in javascript, like so:

var canvas = document.getElementById("canvas")
canvas.width = window.innerWidth
canvas.height = window.innerHeight

right? Well it works at first but then when you resize the browser's window the canvas doesn't get resized with it. Fine then just add an event listener and resize the canvas every time the browser's window is resized:

var canvas = document.getElementById("canvas")

window.addEventListener("resize", function() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
})

But the problem with that is when the browser's window is resized the window.innerWidth and window.innerHeight properties aren't actually updated. I'm aware that there are many other properties that represent the width and height of the window, but none of them seem to update either.
So how do you really make a canvas full screen?

Answered by Coder100 (18123) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (18123)

pixel ratio is what you are looking for
https://stackoverflow.com/questions/15661339/how-do-i-fix-blurry-text-in-my-html5-canvas

you see, some computers have more pixels so you need to fix that