画布颜色匹配范围

时间:2015-07-23 10:35:11

标签: javascript canvas

我当前的代码扫描画布上的颜色,然后将其从画布中移除并移动到下一个像素。我想要实现的是颜色搜索的强度。所以我们发现了类似的颜色,而不仅仅是一种RGBA颜色。

这是可能的,这是我用一种颜色的工作代码。

当前代码

id

1 个答案:

答案 0 :(得分:2)

免责声明

这个答案基于OP的代码,可能不是最好的方法。

要检查实际像素是否在您通过阈值定义的范围内,您可以使用if-statement这样的if语句:
if(data[i]>=color[0]-threshold/2 && data[i]<=color[0]+threshold/2 && data[i+1]>=color[1]-threshold/2 && data[i+1]<=color[1]+threshold/2 && data[i+2]>=color[2]-threshold/2 && data[i+2]<=color[2]+threshold/2

或者,为了更清楚,您可以创建一个检查此fork的函数:

function isBetween(value, i){
    return (value>=color[i]-threshold/2 && value<=color[i]+threshold/2)
}

然后像这样使用它:

if( isBetween(data[i],i%4) && isBetween(data[i+1],i%4+1) && isBetween(data[i+2],i%4+2) ){ doSomething() }

完整的例子:

var canvasEl = document.createElement('canvas');
var context = canvasEl.getContext('2d');
document.body.appendChild(canvasEl);
var imageData;

var img = new Image();
img.crossOrigin='anonymous';
img.onload = function(){
  canvasEl.height = 250;
  canvasEl.width = 400;
  context.drawImage(this, 0,0,canvasEl.width,canvasEl.height);
  imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height);
  }
// image by Levanne (https://www.flickr.com/photos/lfphotos/14282259549/) CC BY-SA 2.0
img.src = 'https://dl.dropboxusercontent.com/s/te5g7s1lh122quy/1024px-Levanne_%2814282259549%29.jpg?dl=0';

var input = document.querySelector('input');
input.addEventListener('change', colorIntesityThreshold, false);


function colorIntesityThreshold(){
    var threshold = this.value;
    var data = imageData.data;
    var newData = new Uint8ClampedArray(data);
    //RGB
    var color = [50, 100, 255, 1];

    function isBetween(val, i){
      return (val>=(color[i]-threshold/2) && val<=(color[i]+threshold/2))
    }

    for (var i = 0, n = data.length; i <n; i += 4) {

      if( isBetween(data[i],i%4) && isBetween(data[i+1],i%4+1) && isBetween(data[i+2],i%4+2) ){

           newData[i+3]=0;
      }
    }
    var newImg = new ImageData(newData, canvasEl.width,canvasEl.height);
    context.putImageData(newImg, 0, 0);
}
<input type="range" min="0" max="255" value="0"/>