在 Canvas 上绘制灰度图标(具有透明背景的 png 图像)时,有没有快速着色的方法?通过着色我的意思是将灰度图标变成绿色(给定颜色的阴影而不是灰色以匹配给定的颜色主题)
我知道我可以手动操作每个像素,但也许有一些更自动化的方法?
最佳答案
使用合成将灰度图像重新着色为“绿色”。
使用合成比像素操作更快,而且您不会违反跨域安全限制(如果您改为使用 getImageData
,就会发生这种情况)。
- 创建一个完全绿色的图像版本。
- 在 Canvas 上绘制灰度图像。
- 设置
globalCompositeOperation='color'
,这会使现有的灰度像素重新着色(“重新着色”),并在顶部绘制像素。 - 在 Canvas 上绘制全绿色图像。
“颜色”合成会将灰度变成绿度。
注意:需要具有混合功能的现代浏览器(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/