在JavaScript中复制部分CSS灰度过滤器?
我可以轻松地将图像转换为全灰度版本。我不能做的是复制部分灰度缩放。比如说,在JavaScript中复制部分CSS灰度过滤器?,javascript,html,css,html5-canvas,Javascript,Html,Css,Html5 Canvas,我可以轻松地将图像转换为全灰度版本。我不能做的是复制部分灰度缩放。比如说, .image { filter: grayscale(0.5); } CSS中应用的此过滤器将仅使图像部分变为灰度。我想在画布图像上的JavaScript中执行同样的操作。谁能帮我一下吗 我知道如何使图像完全灰度化。我正在寻找一种使效果不那么强烈的方法,我想使用JavaScript画布来实现它。 以上所有图像都应用了不同强度的灰度过滤器。使用ctx.globalCompositeOperation=“satura
.image {
filter: grayscale(0.5);
}
CSS中应用的此过滤器将仅使图像部分变为灰度。我想在画布图像上的JavaScript中执行同样的操作。谁能帮我一下吗
我知道如何使图像完全灰度化。我正在寻找一种使效果不那么强烈的方法,我想使用JavaScript画布来实现它。
以上所有图像都应用了不同强度的灰度过滤器。使用ctx.globalCompositeOperation=“saturation” 使用globalCompositeOperation类型
“源覆盖、较亮、较暗、源顶部、源输入、源输出、目标覆盖、目标顶部、目标输入、目标输出、复制、异或、乘法、屏幕、覆盖、颜色减淡、颜色烧伤、强光、柔和光、差异、排除、色调、饱和度、颜色、亮度”
并非所有浏览器都支持所有操作(最值得注意的是FF不支持darker
usemultiply
),但chrome、Edge和Firefox支持上述所有其他浏览器
更多关于饱和度和黑白颜色的内容[2]如下,这两种方法都能很好地控制效果的大小
使用饱和度增加颜色对比度
使用以下选项增加图像的饱和度级别:
ctx.globalCompositeOperation = 'saturation';
效果的大小可以通过alpha设置或填充覆盖中的饱和度大小来控制
// Render the image
ctx.globalCompositeOperation='source-atop';
ctx.drawImage(image, 0, 0);
// set the composite operation
ctx.globalCompositeOperation ='saturation';
ctx.fillStyle = "red";
ctx.globalAlpha = alpha; // alpha 0 = no effect 1 = full effect
ctx.fillRect(0, 0, image.width, image.height);
颜色转换为黑白
通过以下方式从图像中移除颜色:
ctx.globalCompositeOperation = 'color';
效果的大小可以通过alpha设置进行控制
// Render the image
ctx.globalCompositeOperation='source-atop';
ctx.drawImage(image, 0, 0);
// set the composite operation
ctx.globalCompositeOperation='color';
ctx.fillStyle = "white";
ctx.globalAlpha = alpha; // alpha 0 = no effect 1 = full effect
ctx.fillRect(0, 0, image.width, image.height);
所谓部分,是指画布的一部分吗?@Roberrrt否,让我添加一幅图像。:)将灰度图像放在原始图像上并降低不透明度?或者其他方式around@JariPekkala类似这样的东西,但我不知道怎么做。:)你用错了词。你没有使它变灰,而是“去饱和””“是的。一旦你在谷歌上写下这些,就会有很多结果。示例:除此之外,Firefox以及Chrome/Opera现在都直接支持带有上下文的CSS过滤器,因此您可以设置
ctx.filter=“grayscale(0.5)”代码>虽然不确定Edge,但是在性能方面应该没有什么区别,因为CSS和上下文混合模式是相同的。只要提到这是一个未来的选择,它可以在完全支持的情况下简化整个过程。
// Render the image
ctx.globalCompositeOperation='source-atop';
ctx.drawImage(image, 0, 0);
// set the composite operation
ctx.globalCompositeOperation='color';
ctx.fillStyle = "white";
ctx.globalAlpha = alpha; // alpha 0 = no effect 1 = full effect
ctx.fillRect(0, 0, image.width, image.height);