我正在尝试绘制剪裁到区域1的shape1和剪裁到区域2的shape2。我自然的假设是以下内容会达到我想要的效果。
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
调用将被忽略。
所以,我有两个问题。
- html5 canvas 中的剪切工作方式有什么逻辑吗?
- 我怎样才能完成我最初计划要做的事情?
任何帮助解决这个问题的帮助都是值得赞赏的!
最佳答案
始终使用 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>
关于javascript - 剪切区域没有被restore()清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32262436/