I'm currently trying to receive the width and height of a canvas. The canvas is using a style parameter as you can see in the following code:
I've tried to get the value using
console.log(ctx.width); which returned a undefined value. I think the problem occurs because im using the style tag to set the canvas to a autosize.
How could i receive the canvas width and height in another way?
I appreciate any kind of suggestions.
The canvas is a special case when it comes to the width and height.
canvas.style.height define the width and height of the canvas as displayed on the page.
canvas.height properties define the size of the canvas in pixels or the resolution of the canvas. The canvas resolution does not always match the canvas display size.
You can get the canvas resolution by just getting the width and height properties.
var width = canvas.width; var height = canvas.height;
The canvas resolution will not have any units at the end so can be directly converted to a
canvas.height properties are always in pixels.
If you do not set the
canvas.height properties the canvas resolution will default to 300 by 150.
You can access the 2D context canvas via the
context.canvas property. The context does not have a width and height property.
// get resolution var width = ctx.canvas.width; var height = ctx.canvas.height; // get display size. Note values will have units eg px,em,% var displayWidth = ctx.canvas.style.width; var displayHeight = ctx.canvas.style.height;
Oh and as pointed out in the comments. Style attributes will only be available if set.