Categories
JavaScript Answers

How to Make the HTML Canvas Full Screen with JavaScript?

Spread the love

To make the HTML canvas full screen with JavaScript, we can set the canvas width and height to the browser window width and height respectively.

For instance, we can create a canvas with:

<canvas style="border:1px solid #000000;">
</canvas>

Then we can make sure the canvas is always set to the width and height of the window by writing:

const canvas = document.querySelector("canvas");

const resize = () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
}

resize()
window.addEventListener('resize', resize)

We select the canvas with document.querySelector .

Then we add the resize function that sets the canvas width and height to the window.innerWidth and innerHeight respectively to resize the canvas to fit the window.

We call the resize function to resize the canvas when the page loads.

And then we watch the resize event of the window with window.addEventListener and set resize as the callback to make sure the canvas is resized when the browser tab is resized.

By John Au-Yeung

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

2 replies on “How to Make the HTML Canvas Full Screen with JavaScript?”

Hi there. I get scrollbars unless I subtract some pixels. How do I get the whole screen without invoking them?

You can hide the overflow with overflow CSS style set to hidden.

And then you can set the canvas width and height to match the screen’s dimensions.

Leave a Reply

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