How to use HTML5 Canvas Clipping Region

This article describe about HTML5 Canvas Clipping Region.
  • 2752

HTML5 Canvas Clipping Region

Clipping means cut the any region of original canvas shape using the clip() method. All future grawings will be limited if once a region is clipped, and i won't to access the other region on the canvas. If  save the current canvas region using the save() before you any clipping, and restore it any time in the future.

In HTML5 to define clipping region first draw a path then use clip() method.

Syntax

<script>

  context.clip();

</script>

 

Example:

<!DOCTYPE HTML>

<html>

  <head>

    <style>

      body {

        margin: 0px;

        padding: 0px;

      }

      #myownCanvas {

        border: 1px solid #9C9898;

      }

    </style>

    <script>

        window.onload = function () {

            var canvas = document.getElementById("myownCanvas");

            var context = canvas.getContext("2d");

            var a = canvas.width / 2;

            var b = canvas.height / 2;

            var radius = 85;

            var offset = 60;

            context.save();

            context.beginPath();

            context.arc(a, b, radius, 0, 2 * Math.PI, false);

            context.clip();

            context.beginPath();

            context.arc(a - offset, b - offset, radius, 0, 2 * Math.PI, false);

            context.fillStyle = "Black";

            context.fill();

            context.beginPath();

            context.arc(a + offset, b, radius, 0, 2 * Math.PI, false);

            context.fillStyle = "pink";

            context.fill();

            context.beginPath();

            context.arc(a, b + offset, radius, 0, 2 * Math.PI, false);

            context.fillStyle = "Brown";

            context.fill();

            context.restore();

            context.beginPath();

            context.arc(a, b, radius, 0, 2 * Math.PI, false);

            context.lineWidth = 3;

            context.strokeStyle = "Red";

            context.stroke();

        };

    </script>

  </head>

  <body>

    <canvas id="myownCanvas" width="578" height="200"></canvas>

  </body>

</html>

 

Output

HTML5 canvas clipping pic3.jpg

You may also want to read these related articles Click here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.