我找到了许多用于剪切弧外部区域的示例(例如: this example )。我似乎无法弄清楚如何在弧形内部进行剪辑。
这是我目前如何裁剪外部区域的示例,这与我想要的本质相反:
ctx.save();
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
ctx.clip();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.shadowBlur = 10;
ctx.shadowOffsetX = shadowOffset;
ctx.shadowColor = '#000000';
ctx.strokeStyle = '#000000';
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
ctx.stroke();
ctx.restore();
最佳答案
可用选项
对于不规则形状,您可以使用两种技术:
恕我直言,使用实际剪辑模式或复合模式的更好选择
destination-out
.正如 markE 在他的回答中所说
xor
也可用,但 xor 只反转 alpha 像素,不删除 RGB 像素。这适用于没有透明度的实体图像,但是如果您有具有透明度的现有像素,这些可能会给您带来相反的效果(变得可见),或者如果您稍后使用异或模式并在顶部绘制其他内容,“剪切”区域将再次显示。剪裁
通过使用剪辑,您可以简单地使用
clearRect
清除路径定义的区域。示例:
/// save context for clipping
ctx.save();
/// create path
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.closePath();
/// set clipping mask based on shape
ctx.clip();
/// clear anything inside it
ctx.clearRect(0, 0, offset, offset);
/// remove clipping mask
ctx.restore();
ONLINE DEMO FOR CLIPPING 源图片 :具有部分半透明像素和完全透明的图像,背景中的白色通过 -
结果:
我们在上面打了一个洞,背景显示出来:
复合模式:目的地输出
使用复合模式
destination-out
将像剪辑一样清除像素:ctx.beginPath();
ctx.arc(offset * 0.5, offset * 0.5, offset * 0.3, 0, 2 * Math.PI);
ctx.closePath();
/// set composite mode
ctx.globalCompositeOperation = 'destination-out';
ctx.fill();
/// reset composite mode to default
ctx.globalCompositeOperation = 'source-over';
ONLINE DEMO FOR COMPOSITE MODE :结果:
与剪切相同
destination-out
删除像素。复合模式:异或
使用
xor
在这种情况下存在透明像素( see online example here ):只有 alpha 值被反转。由于我们没有实心像素,alpha 不会从 255 变为 0(
255 - 255
)而是 255 - actual value
使用此模式会导致背景未清除。(如果您使用相同的模式再次绘制,“删除”的像素将被恢复,因此可以以其他方式使用)。
关于canvas - 如何在 HTML5 Canvas 中剪辑 INSIDE 形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18988118/