Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 271
heyitsqueon Avatar asked Oct 25 '25 21:10

heyitsqueon


1 Answers

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.

like image 133
Blindman67 Avatar answered Oct 27 '25 10:10

Blindman67