Categories
JavaScript Answers

How to get the width and height of a HTML5 canvas with JavaScript?

Spread the love

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.

By John Au-Yeung

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

Leave a Reply

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