Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating multiple clipping paths in HTML5 canvas using loop

I cannot create multiple clipping paths in canvas. With this code, if i=1, I get the clipping path working correctly. For i>1, I only see clipping if the paths are overlapping. Otherwise, nothing is drawn to the canvas.

    function draw() {
        var ctx = document.getElementById('canvas').getContext('2d');

        for (var i = 0; i < 5; i++) {
            ctx.beginPath();
            var x = 25 + 25 * i; // x coordinate
            var y = 75; // y coordinate
            var radius = 20; // Arc radius
            var startAngle = 0; // Starting point on circle
            var endAngle = Math.PI * 2; // End point on circle
            var anticlockwise = true; // clockwise or anticlockwise

            ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);

            ctx.clip();

        }

       ctx.fillStyle = "#000000";
        ctx.fillRect(0, 0, 800, 150);

    }

If it is not possible to have multiple clipping masks on the canvas, is there another compositing method that is the same as clipping mask?

like image 515
interwebjill Avatar asked Oct 29 '25 14:10

interwebjill


1 Answers

If you wish to have multiple shapes in your clip area you need to define all the shapes then apply the clip. If you set the clip after adding each shape you end up clipping only inside the previous clip.

So move ctx.clip() to after the for loop, it need only be called once, and move the ctx.beginPath() to before the loop.

like image 82
Blindman67 Avatar answered Nov 01 '25 04:11

Blindman67



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!