javascript - 绘制透明形状时覆盖在 Canvas 上绘制的内容

标签 javascript html canvas transparency

我看不到这已经发布了,所以就在这里。

假设我在 Canvas 上画了 2 个正方形。

var c = document.getElementById('test'), ctx = c.getContext('2d');
ctx.fillStyle = "rgba(0,0,255,0.5)";
ctx.beginPath();
ctx.moveTo(25, 0);
ctx.lineTo(50, 50);
ctx.lineTo(0, 50);
ctx.lineTo(25, 0);
ctx.fill();
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.beginPath();
ctx.moveTo(50, 0);
ctx.lineTo(75, 50);
ctx.lineTo(25, 50);
ctx.lineTo(50, 0);
ctx.fill();

这会产生这个图像:

enter image description here

如果我将 globalAlpha 更改为 0.5,我会得到以下结果:

enter image description here

但是,我想制作这个:

enter image description here

就像这样,所有像素都是透明的,其下方的任何图像都会显示,但红色三 Angular 形创建的像素将覆盖绘制它的现有蓝色三 Angular 形。

并且 ctx.globalComposisteOperation 在这种情况下似乎没有帮助,因为它还考虑了透明度以及我想保留两个正方形的事实。

有没有办法用当前的方法来做到这一点?

最佳答案

在绘制之前使用合成清除红色三 Angular 形。

使用合成比剪辑稍好一些,因为您不必清除剪辑。清除剪辑需要保存整个上下文状态,然后恢复该上下文状态——涉及许多属性。合成只需要来回更改 1 个属性。

enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// fill the blue rect
ctx.fillStyle = "rgba(0,0,255,0.5)";
ctx.beginPath();
ctx.moveTo(25, 0);
ctx.lineTo(50, 50);
ctx.lineTo(0, 50);
ctx.lineTo(25, 0);
ctx.fill();

// define the red rect path
ctx.beginPath();
ctx.moveTo(50, 0);
ctx.lineTo(75, 50);
ctx.lineTo(25, 50);
ctx.lineTo(50, 0);

// clear the red rect path using compositing
ctx.globalCompositeOperation='destination-out';
ctx.fillStyle='black';
ctx.fill();
ctx.globalCompositeOperation='source-over';

// fill the red rect
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.fill();
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=512 height=512></canvas>

关于javascript - 绘制透明形状时覆盖在 Canvas 上绘制的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39237823/

相关文章:

javascript - ondrop 事件未触发

javascript - 绘制到 html Canvas 中的 png 图像质量差

javascript - 在没有多个 Canvas 的情况下对 Canvas 进行分层

javascript - 我如何从检查元素中知道cpanel中的文件源代码?

javascript - 如何在 React Native 中正确管理 map 初始状态?

javascript如何切换window.location属性的路径名和重定向

javascript - 如何使用结构指令?

jquery - slideToggle 留下空白空间

jquery - 具有不同尺寸图像的物体高度

wpf - 如何了解 Canvas.Children 中对象的类型