HTML | canvas closePath() Method

The canvas beginPath() method is used to create a path from the current point back to the starting point. After calling the closePath() method, we can use stroke() method to draw the path, the fill() method to fill the path with black color as the default and fillStyle property to fill with another color or gradient or pattern.

Syntax:

context.closePath();

Example 1: This example does not use fill() method to fill the close path.



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
      
<head
    <title
        HTML canvas closePath() Property 
    </title
</head
  
<body style="text-align:center;"
      
    <h1 style="color:green">
        GeeksforGeeks
    </h1
      
    <h2>HTML canvas closePath() Property</h2
      
    <canvas id="GFG" width="500" height="300">
    </canvas
      
    <script>
        var id_cont = document.getElementById("GFG");
        var context = id_cont.getContext("2d");
        context.beginPath();
        context.moveTo(450, 0);
        context.lineTo(120, 200);
        context.lineTo(160, 20);
        context.closePath();
        context.stroke();
    </script>
</body
  
</html>    

chevron_right


Output:

Example 2: This example uses fill() method to fill the closed path.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
      
<head
    <title
        HTML canvas closePath() Property 
    </title
</head
  
<body style="text-align:center;"
      
    <h1 style="color:green">
        GeeksforGeeks
    </h1
      
    <h2>HTML canvas closePath() Property</h2
      
    <canvas id="GFG" width="500" height="300">
    </canvas
      
    <script>
        var id_cont = document.getElementById("GFG");
        var context = id_cont.getContext("2d");
        context.beginPath();
        context.moveTo(30, 20);
        context.lineTo(75, 100);
        context.lineTo(100, 150);
        context.lineTo(270, 150);
        context.closePath();
        context.fill();
    </script>
</body
  
</html>

chevron_right


Output:

Supported Browsers: The browsers supported by canvas beginPath() method are listed below:

  • Google Chrome
  • Internet Explorer 9.0
  • Firefox
  • Opera
  • Safari


My Personal Notes arrow_drop_up

Budding Web DeveloperKeen learnerAverage CoderDancer&Social Activist

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.