Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/koolBW.png";
function start(){

    // create a fully green version of img
    var c=document.createElement('canvas');
    var cctx=c.getContext('2d');
    c.width=img.width;
    c.height=img.height;
    cctx.drawImage(img,0,0);
    cctx.globalCompositeOperation='source-atop';
    cctx.fillStyle='green';
    cctx.fillRect(0,0,img.width,img.height);  
    cctx.globalCompositeOperation='source-over';

    // draw the grayscale image onto the canvas
    ctx.drawImage(img,0,0);

    // set compositing to color (changes hue with new overwriting colors) 
    ctx.globalCompositeOperation='color';

    // draw the fully green img on top of the grayscale image
    // ---- the img is now greenscale ----
    ctx.drawImage(c,0,0);
    
    // Always clean up -- change compositing back to default
    ctx.globalCompositeOperation='source-over';
}
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=256 height=256></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...