我想要清除某个画布区域中的描边矩形。我最初的想法是,我只需要使用相同的参数再次调用context.strokeRect函数,并在前面将strokeStyle更改为transparent。然而,它并不起作用。为什么以及如何修复它?请注意,我只想清除矩形的笔划(边框),而不是里面的所有内容。
编辑:我只想清除边框,而不是里面的所有内容,所以我不能使用clearRect()方法。此外,我不能清除整个画布并重新绘制它,因为画布包含动画。
发布于 2017-05-20 04:08:28
下面的示例有两个画布。background只有一些文本。然后我用“红色”填充foreground画布,并使用globalCompositeOperation "destination-out"删除像素。我还将alpha设置为0.5,并减半删除一些像素。
const ctxB = background.getContext("2d");
const ctxF = foreground.getContext("2d");
ctxB.textAlign = "center";
ctxB.textBaseline = "middle";
ctxB.font ="20px arial";
ctxB.fillText("Some Background text",150,25);
ctxB.fillText("Some Background text",150,75);
ctxB.fillText("Some Background text",150,125);
ctxF.lineJoin = "round";
ctxF.fillStyle = "red";
ctxF.fillRect(0,0,300,150);
ctxF.lineWidth = 8;
ctxF.globalCompositeOperation = "destination-out";
ctxF.strokeRect(25,25,250,100);
ctxF.fillRect(75,50,150,50);
ctxF.globalAlpha = 0.5;
ctxF.fillRect(65,40,170,70);
ctxF.globalCompositeOperation = "source-over";canvas {
position : absolute;
top : 0px;
left: 0px;
}<canvas id = "background"></canvas>
<canvas id = "foreground"></canvas>
https://stackoverflow.com/questions/44076353
复制相似问题