HTML Canvas - clip() Method



The HTML Canvas clip() method of CanvasRenderingContext2D interface can be used to change the current available path on the Canvas region into new clipping region.

We can change the clip region by adding various styles and current path. This particularly clips the previous path and add the new path data into it.

Syntax

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

CanvasRenderingContext2D.clip(path, fillrule);

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1 path

Path to be used to apply the clip method.

2 fillrule

The algorithm to apply to check the point is in or out of the clipping region. The possible values for this method are −

  • non-zero

  • even-odd

Return value

The clipping region formed to the current path is rendered on the canvas element.

Example

The following example uses HTML Canvas clip() method to draw a circle on the Canvas element and clip some of the region inside it.

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

Output

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

HTML Canvas Clip Method

Example

The following program draws a rectangle onto the Canvas element and clips some of the region inside it using clip() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="260" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.beginPath();
      context.rect(20, 20, 200, 150);
      context.stroke();
      context.clip();
      context.fillStyle = 'grey';
      context.fillRect(0, 0, 150, 100);
   </script>
</body>
</html>

Output

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

HTML Canvas Clip Method
html_canvas_paths.htm
Advertisements