How to clip a region using html5 Canvas

The clip() method is used to clip a region of any shape and size from the original canvas.



<!DOCTYPE html>
<html>
    <head>
        <title>Drawing </title>
    </head>
    <body>

        <canvas id ="myCanvas" width ="600" height ="400" style="border: 1px solid blue;" >
        </canvas>

        <script>
            var canvas = document.getElementById('myCanvas');
                var context = canvas.getContext('2d');
                // Draw a red circle
            context.beginPath();
            context.arc(60, 60, 40, 0, Math.PI * 2, false);
            context.closePath();
            context.fillStyle = "#ff0000";
            context.fill();

            // Set the clipping area
            context.beginPath();
            context.rect(0, 0, 300, 60);
            context.clip();

            // Draw the circle again
            context.beginPath();
            context.arc(150, 60, 40, 0, Math.PI * 2, false);
            context.closePath();
            context.fillStyle = "#ff0000";
            context.fill();

        </script>

        
    </body>
</html>

——————————————————-

using html5 canvas clipping region tutorial code out put

html5 canvas tutorial  Clipping region using html5 canvas
—————- ———————-

clipping region tutorial live demo on codepen

[codepen_embed height=500 theme_id=1 slug_hash=’yyjBJK’ user=’aslamwaqar’ default_tab=’html’

animations=’run’]

[/codepen_embed]
—————————————

the clipping region and other html5 canvas live demo

 

Codepen.io
—————————————

For further reading check

Diveintohtml5.info
www.html5canvastutorials.com

Next Lecture consist of the new lectures

Author: Habibullah Qamar

Its me Habib Ullah Qamar working as a Lecturer (Computer Sciences) in Pakistan. I have an MS(M.Phil) degree in computer sciences with specialization in software engineering from Virtual University of Pakistan Lahore. I have an experience of more than 15 years in the filed of Computer Science as a teacher. Blog Writing is my passion. I have many blogs, This one is special made with the aim of providing 100% Free online coaching and training to the students of under-graduate and postgraduate classes. Most of the students enrolled in computer sciences, information technology, software engineering and related disciplines find it difficult to understand core concepts of programming and office automation. They find difficult in understanding and solving their assignments.

Leave a Reply

Your email address will not be published. Required fields are marked *