Open In App

How to Set the height and width of the Canvas in HTML5?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The canvas element is a part of HTML5 which allows us for dynamic, scriptable rendering of 2D shapes and bitmap images, facilitating the creation of games, graphs, animations, and compositions.

To set the height and width of the canvas in HTML5, we can utilize the height and width attributes within the <canvas> tag, specifying pixel values to define the canvas dimensions.

Different Approaches to Set the height and width of Canvas in HTML5

Table of Content

1. Using HTML Attributes:

Using HTML attributes, specify the canvas dimensions by adding width and height attributes within the <canvas> tag, defining pixel values to establish the canvas size for rendering graphics in HTML5.

Syntax:

 <canvas width="300" height="300"> HTML Contents... </canvas>

Example: In this example, we use the canvas element with width and height attributes set to 300 pixels each.

HTML




<!DOCTYPE html>
<html>
    <body>
        <h1 style="color:green">
            Welcome To GeeksForGeeks
        </h1>
        <h1>
            Canvas Height and Width Attributes
        </h1>
        <canvas id="Canvas"
            width="300"
            height="300"
            style="border:3px solid">
        </canvas>
        <script>
            let c = document.getElementById("Canvas");
            let ctx = c.getContext("2d");
            ctx.fillStyle = "Green";
            ctx.fillRect(100, 100, 100, 100);
        </script>
    </body>
</html>


Output:

Using HTML Attributes

2. Using CSS:

To set the height and width of a canvas in HTML5 using CSS, target the canvas element in CSS and apply the width and height properties, specifying pixel values to define the canvas dimensions.

Syntax:

  #myCanvas {
        margin: 20px;
        padding: 20px;
        background: #ffffff;
        border: 3px solid green;
        width: 300px;
        height: 190px;
    }

Example: In this example we applies CSS styles to the canvas element with the ID “myCanvas,” setting its width and height to 300px and 190px respectively, along with margin, padding, background, and border properties.

HTML




<!DOCTYPE html>
<html>
<style>
    #myCanvas {
        margin: 20px;
        padding: 20px;
        background: #ffffff;
        border: 3px solid green;
        width: 300px;
        height: 190px;
    }
</style>
 
<body>
    <h1 style="color:green">
        Welcome To GeeksForGeeks
    </h1>
    <h1>
        Canvas Height and Width
    </h1>
    <canvas id="myCanvas"></canvas>
</body>
 
</html>


Output:

Using CSS



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads