How to Resize HTML5 Canvas to Fit the Window with JavaScript?

Sometimes, we may want to resize an HTML5 canvas to fit the window that it’s in with JavaScript.

In this article, we’ll look at how to resize an HTML5 canvas to fit the window with JavaScript.

Setting the width and height Properties of the Canvas

We can just set the width and height properties of the canvas as the window resizes to set the width and height of the canvas to change its size.

For instance, we can write:

const draw = (canvas) => {
  const ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.arc(95, 50, 40, 0, 2 * Math.PI);
  ctx.stroke();
}

const canvas = document.querySelector("canvas");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
draw(canvas)

window.addEventListener('resize', () => {
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
  draw(canvas)
})

to change the size of the canvas initialize to the window’s dimensions with:

canvas.width = window.innerWidth
canvas.height = window.innerHeight

And we do the same thing in the resize event listener, which we added with the addEventListener method.

When the canvas resizes the content disappears, so they have to be drawn again whenever we resize the canvas by setting the width and height properties.

Set the Size with CSS

We can also set the size of the canvas with CSS to make it fill the screen.

For instance, we can write the following HTML:

<canvas></canvas>

And the following CSS:

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

canvas {
  background-color: #ccc;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

to 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%.

And we can draw on it with:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

We draw a circle with the arc method.

We have the center x and y coordinates, radius, and start and end angles in radians as arguments in this order.

Conclusion

We can resize the canvas to fit the screen with JavaScript or CSS.