How to make a canvas as wide and as high as parent with JavaScript?

Spread the love

To make a canvas as wide and as high as parent with JavaScript, we set the canvas width and height properties.

For instance, we write

const canvas = document.getElementById("theCanvas");
const parent = document.getElementById("parent");
canvas.width = parent.offsetWidth;
canvas.height = parent.offsetHeight;

to select the canvas and the parent element with getElementById.

Then we get the parent‘s offsetWidth and offsetHeight and set them as the canvaswidth and height to make them the same width and height.

Leave a Reply

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