user2111737 user2111737 -4 years ago 517
Javascript Question

How to re-tint a grayscale image on canvas

Is there any quick way to colorize greyscale icon (png image with transparent background) when drawing it on canvas? By colorize I mean turning greyscale icon into lets say greenscale (shades of given color instead of grey to match given color theme)

I know I could manipulate each pixel manually but maybe there's some more automated way?

Answer Source

Use compositing to re-tint a grayscale image into "greenscale".

Using compositing is faster than pixel manipulation and as a bonus you won't run afoul of cross-domain security restrictions (which you do if you instead used getImageData).

  1. Create a fully green version of your image.
  2. Draw your grayscale image on the canvas.
  3. Set globalCompositeOperation='color' which causes existing grayscale pixels to be re-tinted ("re-hued") with pixels drawn on top.
  4. Draw your fully green image on the canvas.

"Color" Compositing will turn the grayscale into greenscale.

enter image description here + enter image description here = enter image description here

Note: requires a modern browser with blending capabilities (Edge not IE)

Example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var img=new Image();
function start(){

    // create a fully green version of img
    var c=document.createElement('canvas');
    var cctx=c.getContext('2d');

    // draw the grayscale image onto the canvas

    // set compositing to color (changes hue with new overwriting colors) 

    // draw the fully green img on top of the grayscale image
    // ---- the img is now greenscale ----
    // Always clean up -- change compositing back to default
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=256 height=256></canvas>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download