如何在HTML5画布中剪辑多个形状的INSIDE并集?

问题描述

我想修剪给定路径的一些圆形或矩形孔。 CanvasRenderingContext2D.clearRect()在这里不起作用,因为我需要显示背景。 我在这里引用了答案: https://stackoverflow.com/a/18993901/3066086

,但是触摸形状时不起作用。 这是演示我的应用程序和结果/所需结果的图片代码

<canvas id="canvas" width = "500" height="500" ></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.rect(0,500,500);
ctx.fillStyle = 'rgba(100,100,1)';
ctx.fill();

ctx.beginPath();
ctx.rect(0,500);
ctx.arc(100,250,50,2 * Math.PI);
ctx.closePath();
ctx.arc(300,2 * Math.PI);
ctx.closePath();
ctx.rect(95,245,200,10);
ctx.clip('evenodd');
ctx.beginPath();
ctx.rect(5,5,400,400);
ctx.fillStyle = 'rgba(255,1)';
ctx.fill();
</script>

结果:

result:

所需结果:

desired result:

解决方法

使用globalCompositeOperation

您可以使用它来裁剪图像ctx.globalCompositeOperation = "destination-out";

的一部分

并且仅绘制到图像的透明部分。 ctx.globalCompositeOperation = "destination-over"

因此,与其先绘制背景,不如绘制外部形状,然后切出所需的东西,然后最后在所有东西后面绘制背景。

示例

const ctx = canvas.getContext('2d');

// draw red box first
ctx.beginPath();
ctx.rect(5,5,400,400)
ctx.fillStyle = "#F00";
ctx.fill();

// Cut out circles using globalCompositeOperation  "destination-out"
ctx.globalCompositeOperation = "destination-out";
ctx.fillStyle = "#000";
ctx.beginPath();
ctx.arc(100,250,50,2 * Math.PI);
ctx.closePath();
ctx.arc(300,2 * Math.PI);
ctx.closePath();
ctx.rect(95,245,200,10);
ctx.fill();

// Add background last using "destination-over";
ctx.globalCompositeOperation = "destination-over";
ctx.rect(0,500,500);
ctx.fillStyle = "#999";
ctx.fill();
<canvas id="canvas" width = "500" height="500" style="width:200px;height:200px;"></canvas>