javascript - 如何在 Canvas 上重新着色灰度图像

标签 javascript image colors html5-canvas

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

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

最佳答案

使用合成将灰度图像重新着色为“绿色”。

使用合成比像素操作更快,而且您不会违反跨域安全限制(如果您改为使用 getImageData,就会发生这种情况)。

  1. 创建一个完全绿色的图像版本。
  2. 在 Canvas 上绘制灰度图像。
  3. 设置 globalCompositeOperation='color',这会使现有的灰度像素重新着色(“重新着色”),并在顶部绘制像素。
  4. 在 Canvas 上绘制全绿色图像。

“颜色”合成会将灰度变成绿度。

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

注意:需要具有混合功能的现代浏览器(Edge 而非 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';
}
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=256 height=256></canvas>

关于javascript - 如何在 Canvas 上重新着色灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174195/

相关文章:

html - 鉴于它是响应式的,我如何才能将我的文本置于图像之上?

jquery 图像调整大小过渡 onMouseOver

java - LibGDX WrappedText 但通过在文本中使用颜色(java)

javascript - 在另一个对象中引用一个 javascript 对象

javascript - 使用 vue.js 和 moment.js 创建倒计时

javascript - knockout .js : manually trigger computed

unix - ncurses 中的颜色对没有使用正确的颜色

javascript - 如何使用 JavaScript 以特定格式显示 Date 对象?

javascript - 如何从 Canvas 上加载的切片图像获取图像?

javascript - 如何防止在 React 中重新渲染随机颜色