javascript - 如何在不去除背景的情况下去除两个矩形的交集?
问题描述
我在画布上绘图,我想删除两个矩形的交集而不删除背景。
红色矩形将是我的背景,我只想删除黄色和蓝色矩形之间的交集而不删除红色。如果我使用该属性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);
解决方案
您应该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>
推荐阅读
- php - 在 PHP 中通过 SQL 准备语句插入图像
- r - 模型的结果可以适合乘以估算的数据集被提取到数据框吗?
- html - 以特定长度包裹的 Flexbox
- python - 使用 matplotlib tricontourf 的相位图
- java - Spring Boot - 使用变量键从 application.yml 注入映射
- angularjs - 有没有办法在不将代码库迁移到 ES6 或 ES5 的情况下将 angular 6 库用于 angularJS 应用程序
- swift - XCode 模拟器和实际设备显示不同的 UI
- css - 删除边框图像和线性背景之间的空间
- actions-on-google - 单击浏览轮播时,它将打开浏览器。如何返回我的操作?
- mysql - 为什么我在加入 has_one 关联时看不到数据库表?