Reputation: 950
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?
Upvotes: 4
Views: 2315
Reputation: 54026
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.
Upvotes: 5