Skip to content
Related Articles

Related Articles

HTML <canvas> Tag

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 15 Jul, 2022
Improve Article
Save Article

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

Note: The <canvas> tag is new in HTML5.

Syntax: 

<canvas id = "script"> Contents... </canvas>

Attributes: The tag accepts two attributes as mentioned above and described below.

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

Example 1: 

HTML




<!DOCTYPE html>
<html>
    <body>
         
        <!-- canvas Tag starts here -->
        <canvas id = "GeeksforGeeks" width = "200"
            height = "100" style = "border:1px solid black">
        </canvas>
        <!-- canvas Tag ends here -->
         
    </body>
</html>

Output: 
 

Example 2: 

HTML




<!DOCTYPE html>
<html>
     
    <body>
        <!-- HTML code to illustrate canvas tag -->
        <canvas id = "geeks" height = "200" width = "200"
            style = "border:1px solid black">
        </canvas>
         
        <script>
            var c = document.getElementById("geeks");
            var cx = c.getContext("2d");
            cx.beginPath();
            cx.arc(100, 100, 90, 0, 2 * Math.PI);
            cx.stroke();
        </script>
           
    </body>
</html>

Output: 

Example 3: 

HTML




<!DOCTYPE html>
<html>
    <body>
         
        <!-- canvas tag starts here -->
        <canvas id = "geeks" width = "200" height = "200"
            style = "border:1px solid black">
        </canvas>
        <!-- canvas tag ends here -->
         
        <script>
            var c=document.getElementById("geeks");
            var cx = c.getContext("2d");
            var grd = cx.createRadialGradient(100,
                            100, 5, 100, 100, 100);
            grd.addColorStop(0, "red");
            grd.addColorStop(1, "green");
            cx.fillStyle = grd;
            cx.fillRect(0, 0, 200, 200);
        </script>
       
    </body>
</html>

Output: 

Supported Browsers:  

  • Google Chrome 1.0 and above
  • Edge 12.0 and above
  • Internet Explorer 9.0 and above
  • Firefox 1.5 and above
  • Opera 9.0 and above
  • Safari 2.0 and above

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!