Search code examples
javascripthtmlhtml5-canvasclipping

HTML5 Canvas not clipping correctly?


I'm wondering if the following code yields appropriate behavior. I feel like the top left square should still be green. that is, if I clip one area, ten restore, then paint in a second area, the canvas paints in BOTH areas. Why?

https://jsfiddle.net/s6t8k3w3/

var my_canvas = document.getElementById('canvas');
var ctx = my_canvas.getContext("2d");

//Make Clipping Path 1
ctx.save();
ctx.rect(20, 20, 100, 100);
ctx.clip();

//Fill Background with Green
ctx.fillStyle = 'rgba(0,255,0,1)';
ctx.fillRect(0, 0, my_canvas.width, my_canvas.height);
//Close Clipping Path 1
ctx.restore();

//Open Clipping Path 2
ctx.save();
ctx.rect(50, 50, 100, 100);
ctx.clip();

//Fill background with Blue
ctx.fillStyle = 'rgba(0,0,255,1)';
ctx.fillRect(0, 0, my_canvas.width, my_canvas.height);

//Draw Line
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(500, 500);
ctx.stroke();

//CloseClipping Path 2
ctx.restore();

Solution

  • You're not actually opening a second clipping path with that second ctx.save(); to do that, you need to call ctx.beginPath()