首页 > 解决方案 > 如何在不去除背景的情况下去除两个矩形的交集?

问题描述

我在画布上绘图,我想删除两个矩形的交集而不删除背景。

只删除黄色和蓝色之间的交点

红色矩形将是我的背景,我只想删除黄色和蓝色矩形之间的交集而不删除红色。如果我使用该属性ctx.globalCompositeOperation = "destination-out";,则会删除背景(红色)。

背景已删除

我怎样才能做到这一点?

我的代码:

ctx.fillStyle = "red";
ctx.fillRect(20, 20, 75, 50);
ctx.fillStyle = "blue";
ctx.globalCompositeOperation = "source-over";
ctx.fillRect(50, 50, 75, 50);
ctx.globalCompositeOperation = "destination-out";
ctx.fillStyle = "yellow";
ctx.fillRect(59,30,75,50);

标签: javascripthtml5-canvas

解决方案


您应该destination-over在绘制红色形状之前使用,并将其放在其他内容之后。

每个 MDN:“在现有画布内容后面绘制新形状。”

所以你使用destination-out排除,然后在后面添加红色形状。

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 75, 50);
ctx.globalCompositeOperation = "destination-out";
ctx.fillStyle = "yellow";
ctx.fillRect(59, 30, 75, 50);
ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 75, 50);
<canvas width="150" height="150" id='canvas'></canvas>


推荐阅读