微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。