HTML5 canvas not cropping correctly?

I am wondering if the following code matches the correct behavior. I feel that the top left square should still be green. that is, if I fixed one area, ten restore, and then paint in the second area, canvas paint in areas of BOTH. 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();
+4
source share
1 answer

In fact, you are not opening a second clipping path with this second ctx.save(); for this you need to callctx.beginPath()

+2
source

All Articles