我正在画shape1剪裁到region1,shape2剪裁成region2。我的自然假设是,以下这些都会得到我想要的效果。
context.save();
context.clip(region1);
context.fill(shape1);
context.restore();
context.save();
context.clip(region2);
context.fill(shape2);
context.restore();然而,令我惊讶的是,第一个restore()并没有取消当前的裁剪区域。相反,第二个区域与第一个区域相结合。这与多个在线消息来源相反,后者声称,当您完成裁剪时,restore()是一条道路。
实例化。您可以看到,第二个fill (蓝色)被裁剪到region1+region2,而不仅仅是region2。
更奇怪的是,这种附加行为是通过使用save/restore调用来实现的。如果我删除它们,那么第二个clip调用就会被忽略。
所以,我有两个问题。
任何帮助,以了解这一点是非常感谢的!
发布于 2015-08-28 02:45:37

始终使用context.beginPath()开始新的路径绘制。
如果不这样做,将导致所有以前的绘图命令与新添加的命令一起重新执行。
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.save();
ctx.beginPath();
ctx.rect(100, 0, 100, 300);
ctx.clip();
ctx.fillStyle = "lime";
ctx.fillRect(0,0,300,300);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.rect(50, 50, 200, 200);
ctx.clip();
ctx.fillStyle = "blue";
ctx.fillRect(0,0,300,300);
ctx.restore();body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }<canvas id="canvas" width=300 height=300></canvas>
https://stackoverflow.com/questions/32262436
复制相似问题