我可以轻松地将图像转换为完全灰度版本。我不能做的是复制部分灰度。例如,
.image {
filter: grayscale(0.5);
}
在CSS中应用的此滤镜仅会将图像部分灰度化。我想在画布图像上的JavaScript中做同样的事情。谁能帮帮我呢?
我知道如何使图像完全灰度。我正在寻找一种方法来减少效果,我想用JavaScript画布来做。
上面的所有图像都使用了不同强度的灰度滤镜。
答案 0 :(得分:0)
使用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);
颜色为黑白
通过
从图像中删除颜色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);