Skip to content Skip to sidebar Skip to footer

Replicate The Partial Css Grayscale Filter In Javascript?

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 i

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

enter image description here

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

enter image description here

Post a Comment for "Replicate The Partial Css Grayscale Filter In Javascript?"