Fabric.js逐像素处理Image对象以更改颜色 [英] Fabric.js manipulate Image object pixel by pixel to change color

查看:220
本文介绍了Fabric.js逐像素处理Image对象以更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个fabric.Image对象的数据,以遍历每个像素,并在给定颜色为另一给定颜色的情况下更改其颜色.但是我不想获取整个画布的数据,而只获取特定对象的数据.像这样-

I want to get the data of an image of a fabric.Image object to loop through each pixel and change its color if it's a given color to another given color. But I don't want to get the data of the entire canvas, only of that specific object. Something like this -

changeColor = (object, targetColor, replacementColor) => {
  data = object.getData();

  for(var i = 0, n = data.length; i<n; i+=4){
    let r = data[i];
    let g = data[i + 1];
    let b = data[i + 2];
    
    if(r === targetColor.r && g === targetColor.g && b === targetColor.b){
      imgd[i] = replacementColor.r;
      imgd[i + 1] = replacementColor.g;
      imgd[i + 2] = replacementColor.b;
      imgd[i + 3] = replacementColor.a;
    }
  }
}

但是我不知道如何获取对象的数据(我知道 getData()不是真正的函数).

But I do not know how to get the data of an object (I know getData() is not a real function).

TL; DR:我想要一种获取Fabric对象(不是整个画布)的图像数据,然后能够操纵其像素并将修改后的图像放回原位的方法.

推荐答案

做到这一点的最佳方法是使用图像过滤器.幸运的是,Fabric提供了具有非常相似功能的图像滤镜- RemoveColor (

The best way to do this is with an image filter, I'd say. Fortunately, Fabric provides an image filter with a very similar functionality - RemoveColor (http://fabricjs.com/docs/fabric.js.html#line23120). We can take that implementation, tweak it a little to replace with a configurable color instead of removing, and that should do the trick.

我们对 RemoveColor 类进行了三项主要更改,以创建我们的 ReplaceColor 类:

There are three main changes we make to the RemoveColor class to create our ReplaceColor class:

  • 添加一个 replacementColor 字段,该字段需要使用4个宽的颜色数组来替换
  • 修改webGL以为替换颜色添加一个额外的参数:
  • Adding a replacementColor field that takes a 4 wide array of the color to replace with
  • Modifying the webGL to take in an extra parameter for the replacement color:
        fragmentSource: 'precision highp float;\n' +
            'uniform sampler2D uTexture;\n' +
            'uniform vec4 uLow;\n' +
            'uniform vec4 uHigh;\n' +
            'uniform vec4 uRep;\n' + // New variable for replacement color
            'varying vec2 vTexCoord;\n' +
            'void main() {\n' +
            'gl_FragColor = texture2D(uTexture, vTexCoord);\n' +
            'if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\n' +
            'gl_FragColor.rgb = uRep.rgb;\n' + // Here we set the color instead of 0-ing out the alpha
            'gl_FragColor.a = uRep.a;\n' +
            '}\n' +
            '}',

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆