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

Spread the love

To get the width and height of an HTML5 canvas with JavaScript, we use the getBoundingClientRect method.

For instance, we write

const canvas = document.getElementById("mycanvas");
const width = canvas.width;
const height = canvas.height;
const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;

to select the canvas with getElementById.

And then we call getBoundingClientRect method to return an object with the width and height of the canvas.

Leave a Reply

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