Get canvas width and height using javascript

Viewed 7493

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.

2 Answers
Related