Sometimes, we want to make canvas as wide and as high as parent with JavaScript.
In this article, we’ll look at how to make canvas as wide and as high as parent with JavaScript.
How to make canvas as wide and as high as parent with JavaScript?
To make canvas as wide and as high as parent with JavaScript, we can set the width and height.
For instance, we write
const canvas = document.querySelector("canvas");
const fitToContainer = (canvas) => {
canvas.style.width = "100%";
canvas.style.height = "100%";
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
};
fitToContainer(canvas);
to define the fitToContainer to set the width and height of the canvas to fit the parent with
canvas.style.width = "100%";
canvas.style.height = "100%";
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
Then we call fitToContainer with canvas to resize the canvas.
Conclusion
To make canvas as wide and as high as parent with JavaScript, we can set the width and height.