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

如何在不删除背景的情况下删除两个矩形的交集?

如何解决如何在不删除背景的情况下删除两个矩形的交集?

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

delete only intersection between the yellow and blue

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

background deleted

我该如何实现?

我的代码

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

解决方法

在绘制红色形状并将其放置在其他内容之后,应使用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,50);
ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "red";
ctx.fillRect(20,20,50);
<canvas width="150" height="150" id='canvas'></canvas>

,

在向图像添加更多内容之前,您需要创建背景的副本。

要复制画布

function copyImage(image) { // image can be any image source
    const copy = document.createElement("canvas");
    copy.width = image.width;
    copy.height = image.height;
    copy.ctx = copy.getContext("2d");
    copy.ctx.drawImage(image,0);
    return copy;
}

一旦拥有背景副本,就可以对图像进行分层。

步骤

  • 首先清除画布
  • 绘制蓝框
  • globalCompositeOperation设置为"destination-out"
  • 绘制黄色框
  • globalCompositeOperation设置为"destination-over"
  • 绘制背景

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

// Create background
ctx.fillStyle = "red";
ctx.fillRect(10,10,200,100);

// copy background
const bgImage = copyImage(canvas);

// Clear canvas
ctx.clearRect(0,300,150);

// Draw the blue box
ctx.fillStyle = "blue";
ctx.fillRect(100,150,70);

// draw yellow to remove pixels
ctx.globalCompositeOperation = "destination-out";
ctx.fillRect(150,70);

// draw background
ctx.globalCompositeOperation = "destination-over";
ctx.drawImage(bgImage,0);

// copy image util function
function copyImage(img,{width,height} = img) { 
  const c = Object.assign(document.createElement("canvas"),height}).getContext("2d");
  c.drawImage(img,0);
  return c.canvas;
}
canvas { border: 2px solid #000 }
<canvas id="canvas"></canvas>

,

您可以尝试将背景设置为红色。

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