Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the width and height of a HTML5 canvas?

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?

like image 412
clamp Avatar asked Oct 27 '10 10:10

clamp


People also ask

How do you find the height and width of a canvas?

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.

How do you specify canvas height and width in the HTML portion of your code?

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).

What is the default height and width of canvas area?

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.


2 Answers

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.

like image 125
andrewmu Avatar answered Sep 22 '22 22:09

andrewmu


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.

like image 23
Bitterblue Avatar answered Sep 19 '22 22:09

Bitterblue