How to resize HTML5 canvas to parent’s size with JavaScript?

Sometimes, we want to resize HTML5 canvas to parent’s size with JavaScript.

In this article, we’ll look at how to resize HTML5 canvas to parent’s size with JavaScript.

How to resize HTML5 canvas to parent’s size with JavaScript?

To resize HTML5 canvas to parent’s size with JavaScript, we can set the canvas’ width and height properties.

For instance, we write:

<div>
  <canvas></canvas>
</div>

to add a div and a canvas.

Then we write:

const canvas = document.querySelector('canvas')
const theDiv = document.querySelector('div')
canvas.width = theDiv.clientWidth;
canvas.height = theDiv.clientHeight;

to resize the canvas to the size of the div by setting the canvas‘s height and width to the theDivs‘s clientHeight and clientWidth properties respectively.

As a result, the size of the canvas is now the same as as the parent div.

Conclusion

To resize HTML5 canvas to parent’s size with JavaScript, we can set the canvas’ width and height properties.
to select the canvas and a div.