How to specify the width and height of the canvas using HTML ?

The <canvas> tag in HTML is used to draw graphics on web page using JavaScript. It can be used to draw paths, boxes, texts, gradient, and adding images. By default, it does not contain borders and text.

Syntax:

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

Attributes: The canvas tag has two attributes which are listed below.

  • height: This attribute is used to set the height of canvas.
  • width: This attribute is used to set the width of canvas.

Example 1:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!-- HTML code to illustrate height and
     width attribute of canvas tag -->
<!DOCTYPE html>
<html>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <h3>
        How to specify the width
        and height of the canvas?
    </h3>
  
    <canvas id="canvasID" height="200" width="200" 
        style="border:1px solid black">
    </canvas>
</body>
</html>

chevron_right


Output:



Example 2:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!-- HTML code to illustrate height and
    width attribute of canvas tag -->
<!DOCTYPE html>
<html>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <h3>
        How to specify the width
        and height of the canvas?
    </h3>
  
    <canvas id="canvasID" height="200" width="200" 
        style="border:1px solid black">
    </canvas>
  
    <script>
        var canvas = document.getElementById("canvasID");
        // Getting a drawing context in the canvas
        var context = canvas.getContext("2d");
        context.beginPath();
        context.arc(100, 100, 90, 0, 2 * Math.PI);
        context.stroke(); 
    </script>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.