How do I get the width and height of a HTML5 canvas?
Solution 1:
It might be worth looking at a tutorial: MDN Canvas Tutorial
You can get the width and height of a canvas element simply by accessing those properties of the element. For example:
var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;
If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:
const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;
Or using the shorter object destructuring syntax:
const { width, height } = canvas.getBoundingClientRect();
The context
is an object you get from the canvas to allow you to draw into it. You can think of the context
as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.
Solution 2:
Well, all the answers before aren't entirely correct. 2 of major browsers don't support those 2 properties (IE is one of them) or use them differently.
Better solution (supported by most browsers, but I didn't check Safari):
var canvas = document.getElementById('mycanvas');
var width = canvas.scrollWidth;
var height = canvas.scrollHeight;
At least I get correct values with scrollWidth and -Height and MUST set canvas.width and height when it is resized.
Solution 3:
The answers mentioning canvas.width
return the internal dimensions of the canvas, i.e. those specified when creating the element:
<canvas width="500" height="200">
If you size the canvas with CSS, its DOM dimensions are accessible via .scrollWidth
and .scrollHeight
:
var canvasElem = document.querySelector('canvas');
document.querySelector('#dom-dims').innerHTML = 'Canvas DOM element width x height: ' +
canvasElem.scrollWidth +
' x ' +
canvasElem.scrollHeight
var canvasContext = canvasElem.getContext('2d');
document.querySelector('#internal-dims').innerHTML = 'Canvas internal width x height: ' +
canvasContext.canvas.width +
' x ' +
canvasContext.canvas.height;
canvasContext.fillStyle = "#00A";
canvasContext.fillText("Distorted", 0, 10);
<p id="dom-dims"></p>
<p id="internal-dims"></p>
<canvas style="width: 100%; height: 123px; border: 1px dashed black">
Solution 4:
The context object allows you to manipulate the canvas; you can draw rectangles for example and a lot more.
If you want to get the width and height, you can just use the standard HTML attributes width
and height
:
var canvas = document.getElementById( 'yourCanvasID' );
var ctx = canvas.getContext( '2d' );
alert( canvas.width );
alert( canvas.height );