Open In App

HTML DOM Canvas Object

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

The DOM Canvas Object is used to represent the HTML <Canvas> element. The <canvas> tag is used to draw graphics in the document using javascript. It is new in HTML5. The canvas element is accessed by getElementById()

Syntax:

accessed by getElementById("id"). 

Where “id” is the ID assigned to the Canvas tag. 

Example 1: In this example, we will use the DOM Canvas Object.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>canvas Tag</title>
</head>
   
<body>
        <h1 style="color:green; Font-size:35px;">
            GeeksForGeeks
        </h1>
        <h2>DOM Canvas Object</h2>
 
        <!-- canvas Tag starts here -->
        <canvas id="geeks"
                height="200"
                width="200"
                style="border:1px solid green">
        </canvas>
   
        <!-- canvas Tag ends here -->
        <br>
        <br>
        <button onclick="myGeeks()">Submit</button>
        <script>
            function myGeeks() {
            let gfg = document.getElementById("geeks");
            let sudo = gfg.getContext("2d");
                sudo.beginPath();
                sudo.arc(100, 100, 90, 0, 2 * Math.PI);
                sudo.stroke();
            }
        </script>
</body>
</html>


Output: 

 

  Example 2: Canvas Object can be created by using the document.createElement method. 

HTML




<!DOCTYPE html>
<html>
<head>
    <style>
        canvas {
            border: 3px solid black;
        }
    </style>
</head>
   
<body>
    <h1 style="color: green; font-size:40px;">
        GeeksForGeeks
    </h1>
    <h2>DOM Canvas Object</h2>
    <button onclick="myGeeks()">
        Submit
    </button>
    <script>
        function myGeeks() {
            let geeks = document.createElement("CANVAS");
            let gfg = geeks.getContext("2d");
            gfg.fillStyle = "green";
            gfg.fillRect(40, 40, 200, 100);
            document.body.appendChild(geeks);
        }
    </script>
</body>
</html>


Output: 

 

Supported Browsers: The browser supported by DOM Canvas Object are listed below:

  • Google Chrome 1
  • Edge 12
  • Internet Explorer 9
  • Firefox 1.5
  • Opera 9
  • Safari 2


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