我正在尝试将clip1剪裁到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()
是完成裁剪时的方法。
Live example。您可以看到第二个填充(蓝色)被剪切到region1 + region2,而不仅仅是region2。
更奇怪的是,使用save
/ restore
调用可以实现这种附加行为。如果我删除它们,则会忽略第二个clip
来电。
所以,我有两个问题。
任何帮助解决这个问题都表示赞赏!
答案 0 :(得分:1)
始终使用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>
&#13;