To obtain the width and height of an HTML5 Canvas, you can directly access them via the Canvas element's properties. Here's a simple example demonstrating how to do this:
First, you need to include a <canvas> element in your HTML document, for example:
html<canvas id="myCanvas" width="300" height="200"></canvas>
In this example, the canvas's initial width is set to 300 pixels and its height to 200 pixels.
Next, you can read the canvas's width and height in JavaScript by accessing its properties:
javascript// Get the canvas element var canvas = document.getElementById('myCanvas'); // Get the canvas width var width = canvas.width; // Get the canvas height var height = canvas.height; console.log("Canvas Width: " + width + ", Height: " + height);
This code first retrieves the Canvas element with the ID myCanvas from the page using the getElementById function. Then, by accessing the width and height properties, it obtains the canvas dimensions and outputs them via console.log.
This method is straightforward and efficient, making it ideal for scenarios requiring dynamic access or modification of canvas dimensions. For instance, in responsive design where you need to adjust the canvas size based on window dimensions, you can use a similar approach to dynamically retrieve and set the canvas dimensions.