Skip to content Skip to sidebar Skip to footer

"saturation" Globalcompositeoperation Without Changing Transparency?

I have a canvas containing art on a transparent background. I desaturate it like this: boardCtx.fillStyle = 'rgba(0, 0, 0, 1.0)'; boardCtx.globalCompositeOperation = 'saturation';

Solution 1:

You can use ctx.filter

The 2D context filter can be used to apply various filters to the canvas.

ctx.filter = "saturate(0%)";
ctx.drawImage(ctx.canvas,0,0);

But this will add to the alpha if there is anti-aliasing / transparency, reducing quality.

Fix Alpha

To fix you need to use the ctx.globalCompositeOperation = "copy" operation.

ctx.filter = "saturate(0%)";
ctx.globalCompositeOperation = "copy";
ctx.drawImage(ctx.canvas,0,0);

// restore defaults;
ctx.filter = "";
ctx.globalCompositeOperation = "source-over";

This will stop the alpha channel from being modified.

Check support.

Warning. Check browser support at bottom of filter page. If no support you will have to use a copy of the canvas to restore the alpha if you use ctx.globalCompositeOperation = "saturation"

Post a Comment for ""saturation" Globalcompositeoperation Without Changing Transparency?"