gpt4 book ai didi

HTML5 Canvas 剪辑与上一个剪辑重叠

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:24 26 4
gpt4 key购买 nike

我有一个奇怪的问题,即在 HTML5 中设置多个剪辑矩形会导致绘图渗入/重叠到之前的剪辑框中,即使每个剪辑框都包含在 ctx.save() - ctx.restore() 中也是如此。

这是代码示例:

var c=document.getElementById("myCanvas2");
var ctx=c.getContext("2d");

// 1st clip
ctx.save();
ctx.rect(20,20,100,100);
ctx.stroke();
ctx.clip();
// draw red rectangle after 1st clip()
ctx.fillStyle="red";
ctx.fillRect(0,0,300,140);
ctx.restore();

// 2nd clip
ctx.save();
ctx.rect(140,20,100,100);
ctx.stroke();
ctx.clip();
// draw blue rectangle after 2nd clip
ctx.fillStyle="blue";
ctx.fillRect(0,0,300,140);
ctx.restore();

还有一个 jsfiddle: http://jsfiddle.net/4eXw9/1/

有没有办法阻止剪辑调用流血/重叠以前的剪辑?

最佳答案

您在第二个剪辑中缺少 beginPath():

// 2nd clip
ctx.save();
ctx.beginPath()
ctx.rect(140,20,100,100);
ctx.stroke();
ctx.clip();

Modified fiddle

发生的事情是您的新矩形与第一个矩形合并,因为描边/填充不会清除路径 - 所以两者都会再次描边/填充。要清除路径,您必须使用 beginPath() 明确清除它。由于路径也是 clip()..

的基础

关于HTML5 Canvas 剪辑与上一个剪辑重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23229289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com