Open In App
Related Articles

How to set the height and width of the canvas in HTML5 ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will learn how to set the height and width of the canvas in HTML5. The canvas element is part of HTML5 which allows us for the dynamic, scriptable rendering of 2D shapes and bitmap images. With the help of HTML5 Canvas, we can make 2D games, graphs, animations, and image compositions. Canvas has two sizes, the size of the element and the size of the drawing surface. The default size for both the element and drawing surface is 300 x 150 screen pixels.

To set the height and width canvas HTML5 has two attributes:

  • Height: With the help of the Height attribute we can set the height.
  • Width: With the help of the Width attribute we can set the width.

Syntax:

<canvas id="myCanvas"> HTML Contents... </canvas>

Example: In this example, we will set the height and width of the <canvas>.

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:

Example: Setting Height and Width using CSS

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 Attributes
      </h1>
    <canvas id="myCanvas"></canvas>
</body>
</html>

                    

Output:



Last Updated : 31 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads