Neena Vivek Neena Vivek - 10 days ago 7
CSS Question

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 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.

enter image description here

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

Answer

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.

This has more on saturation increase the color contrast with saturation can also decrease and Colour to Black and white Both methods give very fine control over the amount of the effect

Comments