HTML Canvas - closePath() Method



The HTML Canvas closePath() method of CanvasRenderingContext2D interface adds a straight line to the current point and closes the current path.

If the path is already closed by the user, the method does not do anything. Even if there is a single path available on the Canvas element, there is no need to close that path.

Syntax

Following is the syntax of HTML Canvas closePath() method −

CanvasRenderingContext2D.closePath();

Parameters

It does not take any parameters and perform only a single operation every time.

Return value

The method when called by the context object completes the path by adding a straight line if it is not completed.

Example

The following example closes the arc drawn onto the Canvas using HTML Canvas closePath() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="200" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.beginPath();
      context.arc(100, 50, 75, 0, 1 * Math.PI);
      context.closePath();
      context.stroke();
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas ClosePath Method

Example

The following program draws two triangles with two edges and closes one of it using the closePath() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="450" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      
      // 1st triangle
      context.beginPath();
      context.moveTo(100, 25);
      context.lineTo(25, 125);
      context.lineTo(175, 125);
      context.stroke();
      context.closePath();
      
      // 2nd triangle
      context.beginPath();
      context.moveTo(300, 25);
      context.lineTo(225, 125);
      context.lineTo(375, 125);
      context.closePath();
      context.stroke();
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas ClosePath Method
html_canvas_paths.htm
Advertisements