How can i get the width and height of the canvas element in JavaScript?
Also, what is the "context" of the canvas I keep reading about?
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.
The height attribute specifies the height of the <canvas> element, in pixels. Tip: Use the width attribute to specify the width of the <canvas> element, in pixels. Tip: Each time the height or width of a canvas is re-set, the canvas content will be cleared (see example at bottom of page).
By default, the browser creates canvas elements with a width of 300 pixels and a height of 150 pixels. You can change the size of a canvas element by specifying the width and height attributes.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With