Sometimes, we want to get the width and height of a HTML5 canvas with JavaScript.
In this article, we’ll look at how to get the width and height of a HTML5 canvas with JavaScript.
How to get the width and height of a HTML5 canvas with JavaScript?
To get the width and height of a HTML5 canvas with JavaScript, we can use the getBoundingClientRect
method.
For instance, we write
const canvas = document.getElementById("mycanvas");
const { width, height } = canvas.getBoundingClientRect();
to select the canvas with getElementById
.
Then we call getBoundingClientRect
to return an object with the width
and height
of the canvas.
Conclusion
To get the width and height of a HTML5 canvas with JavaScript, we can use the getBoundingClientRect
method.