如何解决如何删除画布上两个透明形状的交集?
我想删除两个形状的交集,我知道要做到这一点,我可以使用 XOR 操作。问题是我需要这两个形状是透明的。通过使两个形状透明,不会消除交叉点。
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20,20,75,50);
ctx.fillStyle = "blue";
ctx.globalCompositeOperation = "xor";
ctx.fillRect(50,50,50);
ctx.fillStyle = "rgba(255,0.5)";
ctx.fillRect(150,50);
ctx.fillStyle = "rgba(40,23,0.5)";
ctx.globalCompositeOperation = "xor";
ctx.fillRect(180,50);
</script>
</body>
</html>
注意:在实际问题中,我不可能像建议的那样生成图像here
解决方法
清除重叠图像中像素的一种简单(可能很简单,但确实有效)方法是在各自的画布和主画布上绘制每个图像。
然后我们可以通过像素清除两个图像中的任何像素来遍历主画布像素,即使它只有非常轻微的不透明度。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "rgba(255,0.5)";
ctx.fillRect(150,20,75,50);
ctx.fillStyle = "rgba(40,23,0.5)";
ctx.globalCompositeOperation = "xor";
ctx.fillRect(180,50,50);
var c1 = document.createElement('canvas');
var ctx1 = c1.getContext("2d");
ctx1.fillStyle = "rgba(255,0.5)";
ctx1.fillRect(150,50);
var c2 = document.createElement('canvas');
var ctx2 = c2.getContext("2d");
ctx2.fillStyle = "rgba(40,0.5)";
ctx2.fillRect(180,50);
let imgData = ctx.getImageData(0,300,150);
for (let i=0; i < 300; i++) {
for (let j = 0; j < 150; j++) {
//clear the pixel if both images have opacity>0 there
if (ctx1.getImageData(i,j,1,1).data[3] && ctx2.getImageData(i,1).data[3] ) {
ctx.clearRect(i,1);
}
}
}
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。