Question

I have this weird issue where setting up multiple clip rectangles in HTML5 causes the drawing to bleed/overlap into the previous clip boxes, even when each one is contained in a ctx.save() - ctx.restore().

Here is the code example:

var c=document.getElementById("myCanvas2");
var ctx=c.getContext("2d");

// 1st clip
ctx.save();
ctx.rect(20,20,100,100);
ctx.stroke();
ctx.clip();
// draw red rectangle after 1st clip()
ctx.fillStyle="red";
ctx.fillRect(0,0,300,140);
ctx.restore();

// 2nd clip
ctx.save();
ctx.rect(140,20,100,100);
ctx.stroke();
ctx.clip();
// draw blue rectangle after 2nd clip
ctx.fillStyle="blue";
ctx.fillRect(0,0,300,140);
ctx.restore();

And a jsfiddle: http://jsfiddle.net/4eXw9/1/

Is there a way to stop a clip call from bleeding/overlapping previous clips?

Was it helpful?

Solution

You are missing a beginPath() on the second clip:

// 2nd clip
ctx.save();
ctx.beginPath()
ctx.rect(140,20,100,100);
ctx.stroke();
ctx.clip();

Modified fiddle

What happens is that your new rect is merged with the first one since stroking/filling does not clear the path - so both are stroked/filled again. To clear the path you must explicitly clear it using beginPath(). As the path also is the basis for clip()..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top