Replicate the partial CSS Grayscale filter in JavaScript?

戏子无情 提交于 2020-01-17 05:21:09

问题


I can convert an image to fully grayscale version easily. What I can't do is replicate partial grayscaling. For example,

.image {
  filter: grayscale(0.5);
}

This filter applied in CSS will only turn the image partially grayscale. I want to do the same in JavaScript on a canvas image. Can anyone please help me with that?

I know how to make an image fully grayscale. I am looking for a way to make the effect less intense and I want to do it using JavaScript canvas.

All the images above have the grayscale filter applied with different intensities.


回答1:


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

There are many effect that can be created by using the globalCompositeOperation types "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"

Not all browsers support all operation (Most notable is FF not supporting darker use multiply instead) But chrome, Edge, and Firefox support all the others listed above.

More on saturation and Colour to Black and white][2] below, both methods give very fine control over the amount of the effect

Increase the Color Contrast With Saturation

Increase the saturation level of an image with

ctx.globalCompositeOperation = 'saturation';

The amount of the effect can be controled with the alpha setting or the amount of saturation in the fill overlay

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

Colour to Black and White

Remove color from an image via

ctx.globalCompositeOperation = 'color';

The amount of the effect can be controled with the alpha setting

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



来源:https://stackoverflow.com/questions/40787895/replicate-the-partial-css-grayscale-filter-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!