heyitsqueon
heyitsqueon

Reputation: 43

Get canvas width and height using javascript

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:

<canvas id="ctx" style="height: calc(100vh - 142px); width: 100vw; display: block;"></canvas>

<script type="text/javascript">
    var ctx = document.getElementById("ctx").getContext("2d");

    console.log(ctx.width);

    var socket = io();

    socket.on('newPosition', function(data){
        ctx.clearRect(0, 0, ctx.width, ctx.height);
        ctx.fillText('P', data.x, data.y);
    })
</script>

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.

Upvotes: 4

Views: 10261

Answers (2)

Blindman67
Blindman67

Reputation: 54129

The canvas is a special case when it comes to the width and height.

The canvas.style.width and canvas.style.height define the width and height of the canvas as displayed on the page.

The canvas.width and 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 Number. The canvas.width and canvas.height properties are always in pixels.

If you do not set the canvas.width and 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.

Upvotes: 7

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

Since, you have set the canvas width and height using style attribute, you can get its visible width and height, like this ...

var ctx = document.getElementById("ctx").getContext("2d");

var canvas_width = ctx.canvas.clientWidth;
var canvas_height = ctx.canvas.clientHeight;

console.log(canvas_width, canvas_height);
<canvas id="ctx" style="height: calc(100vh - 142px); width: 100vw; display: block; border: 1px solid black;"></canvas>

Upvotes: 6

Related Questions