gpt4 book ai didi

javascript - 在 JavaScript 中复制部分 CSS 灰度过滤器?

转载 作者:行者123 更新时间:2023-11-28 04:49:34 25 4
gpt4 key购买 nike

我可以轻松地将图像转换为全灰度版本。我不能做的是复制部分灰度。例如,

.image {
filter: grayscale(0.5);
}

在 CSS 中应用的这个滤镜只会将图像部分变成灰度。我想在 JavaScript 中对 Canvas 图像执行相同的操作。谁能帮我解决这个问题?

我知道如何制作完全灰度的图像。我正在寻找一种降低效果的方法,我想使用 JavaScript canvas 来实现。

enter image description here

上面的所有图像都应用了不同强度的灰度滤镜。

最佳答案

使用 ctx.globalCompositeOperation = "saturation"

ctx.drawImage(colourImage,0,0); // draw colour image onto canvas
ctx.globalCompositeOperation = "saturation"; // set the comp mode
ctx.fillStyle = "hsl(0," + Math.floor(amount) + "%,50%); // set a colour with saturation 0-100

// OR use RGB for finer control
ctx.fillStyle = "#FFF"; // white no colour
ctx.globalAlpha = amount; // the amount of saturation you wish to remove 0-1

ctx.fillRect(0,0,colourImage.width,colourImage.height);

使用 globalCompositeOperation 类型可以创建许多效果 "source-over,lighter,darker,source-atop,source-in,source-out,destination-over,destination-atop,destination- in,destination-out,copy,xor,multiply,screen,overlay,color-dodge,color-burn,hard-light,soft-light,difference,exclusion,hue,saturation,color,luminosity”

并非所有浏览器都支持所有操作(最值得注意的是 FF 不支持 darker,而是使用 multiply)但是 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);

enter image description here

彩色转黑白

通过以下方式从图像中移除颜色

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);

enter image description here

关于javascript - 在 JavaScript 中复制部分 CSS 灰度过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40787895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com