如何在画布上重新着色灰度图像

Lap*_*sio 2 javascript image colors html5-canvas

在画布上绘制灰度图标(带透明背景的png图像)时,有没有快速的方法可以着色?通过着色我的意思是将灰度图标变成绿色标度(给定颜色的阴影而不是灰色以匹配给定的颜色主题)

我知道我可以手动操作每个像素,但也许有一些更自动化的方式?

mar*_*rkE 7

使用合成将灰度图像重新着色为"greenscale".

使用合成比像素操作更快,作为奖励,您不会违反跨域安全限制(如果您改为使用,则会执行此操作getImageData).

  1. 创建图像的完全绿色版本.
  2. 在画布上绘制灰度图像.
  3. 设置globalCompositeOperation='color'导致现有灰度像素重新着色("重新调整"),顶部显示像素.
  4. 在画布上绘制完全绿色的图像.

"颜色"合成将灰度变为绿色.

在此输入图像描述 + 在此输入图像描述 = 在此输入图像描述

注意:需要具有混合功能的现代浏览器(Edge not IE)

示例代码和演示:

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';
}
Run Code Online (Sandbox Code Playgroud)
body{ background-color:white; }
#canvas{border:1px solid red; }
Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" width=256 height=256></canvas>
Run Code Online (Sandbox Code Playgroud)