Skip to content
Related Articles

Related Articles

How to set the height and width of the canvas in HTML5 ?
  • Difficulty Level : Expert
  • Last Updated : 12 Mar, 2021

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 composition. Canvas has two sizes, the size of the element and the size of the drawing surface. The default size for both 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 Height attribute we can set the height.
  • Width: With the help of Width attribute we can set the width.

Syntax:

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

Example:

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>
      var c = document.getElementById("Canvas");
      var 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:

My Personal Notes arrow_drop_up
Recommended Articles
Page :