javascript - "saturation"globalCompositeOperation 不改变透明度?

标签 javascript html graphics html5-canvas

我有一个 Canvas ,其中包含透明背景上的艺术。我像这样降低饱和度:

boardCtx.fillStyle = "rgba(0, 0, 0, 1.0)";
boardCtx.globalCompositeOperation = 'saturation';
boardCtx.fillRect(0, 0, boardCanvas.width, boardCanvas.height);

发现透明背景变成了不透明的黑色。我不希望饱和度混合模式改变 Alpha channel ...我做错了什么吗?我当前的解决方案是在去饱和之前复制 Canvas ,并用它来掩盖黑色背景,使其远离去饱和副本,但这涉及另一个 Canvas 和大画......并不理想。

最佳答案

您可以使用ctx.filter

2D 上下文 filter可用于将各种滤镜应用于 Canvas 。

ctx.filter = "saturate(0%)";
ctx.drawImage(ctx.canvas,0,0);

但是如果存在抗锯齿/透明度,这会增加 Alpha,从而降低质量。

修复阿尔法

要修复您需要使用 ctx.globalCompositeOperation = "copy"操作。

ctx.filter = "saturate(0%)";
ctx.globalCompositeOperation = "copy";
ctx.drawImage(ctx.canvas,0,0);

// restore defaults;
ctx.filter = "";
ctx.globalCompositeOperation = "source-over";

这将阻止 Alpha channel 被修改。

检查支持。

警告。检查 filter 底部的浏览器支持页。如果不支持,如果您使用 ctx.globalCompositeOperation = "saturation",则必须使用 Canvas 的副本来恢复 Alpha。

关于javascript - "saturation"globalCompositeOperation 不改变透明度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49313892/

相关文章:

javascript - 如何显示分数计数,显示随机生成的次数?

javascript - 我还需要使用类型 ='text/javascript' 吗?

javascript - 为什么在第二次更改事件后我的文本没有添加到文本区域?

JavaScript onClick 更新 Div

c++ - 使用 Ortho2D 移动当前图形在 GLUT 中不起作用

javascript - 有没有办法设置 slimbox 弹出窗口的最小宽度?

javascript - 在文本中查找格式化问题并从中创建元素

html - 将按钮放入 Canvas 中

r - 如何使用ggplot2在R中制作具有透明背景的图形?

java - 在图像识别尝试中获取空指针