Categories
JavaScript Answers

How to get the width and height of an HTML5 canvas with JavaScript?

Spread the love

To get the width and height of an HTML5 canvas element with JavaScript, you can simply access its width and height properties.

For example we write:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Canvas Width and Height</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="300"></canvas>
    <script>
        // Get the canvas element
        var canvas = document.getElementById('myCanvas');

        // Get the width and height of the canvas
        var canvasWidth = canvas.width;
        var canvasHeight = canvas.height;

        // Output the width and height
        console.log('Canvas width:', canvasWidth);
        console.log('Canvas height:', canvasHeight);
    </script>
</body>
</html>

In this example, we retrieve the canvas element using document.getElementById('myCanvas').

Then, we access the width and height properties of the canvas element to get its dimensions.

Finally, we log the width and height to the console, but you can use these values as needed in your JavaScript code.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *