Categories
JavaScript Answers

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 set the width and height properties.

For instance, we write

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

to select the canvas with querySelector.

Then we get its context with getContext.

Next, we set its width and height to the window width and height, which we get from the innerWidth and innerHeight properties.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *