How to resize HTML5 canvas to fit window with JavaScript?

Spread the love

Sometimes, we want to resize HTML5 canvas to fit window with JavaScript.

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

How to resize HTML5 canvas to fit window with JavaScript?

To resize HTML5 canvas to fit window with JavaScript, we can set the canvas width and height to the window’s width and height.

For example, we write

const draw = () => {
  const htmlCanvas = document.getElementById("c");
  const ctx = htmlCanvas.getContext("2d");
  ctx.canvas.width = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  //...
};

to define the draw function.

In it, we get the canvas with getElementById.

Then we get its context with getContext.

Then we set the width and height of the canvas respectively with

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

window.innerWidth has the window’s width and window.innerHeight has the window’s height.

Conclusion

To resize HTML5 canvas to fit window with JavaScript, we can set the canvas width and height to the window’s width and height.

Leave a Reply

Your email address will not be published.