比较上下文strokestyle和画布中像素的rbg

时间:2013-07-23 09:19:45

标签: javascript html5 canvas

我想要一个检查画布中笔画和像素颜色的函数。如果画布和笔划中的像素颜色相同,则不要更改笔触的颜色。我尝试过下面的功能,但它不起作用。知道怎么做到这一点?感谢

//this line gets pixel data
pixels = context.getImageData(0, 0, canvas.width, canvas.height);
var linecolor = context.strokeStyle;
if ((linecolor) === (colour.r && colour.g && colour.b)){
    context.strokeStyle = "rgb(255,255,0)"
    }

    function getpixelcolour(x, y) {
    var index = ((y * (pixels.width * 4)) + (x * 4));
    return {
    r: pixels.data[index],
    g: pixels.data[index + 1],
    b: pixels.data[index + 2],
    a: pixels.data[index + 3]
    };
}

1 个答案:

答案 0 :(得分:0)

以下是根据笔划和现有像素沿线更改像素颜色的方法。

首先,您需要从开始到结束沿着该线获得XY坐标:

假设:

var startPt={x:50,y:50}
var endPt={x:85,y:25}

您可以沿着该线获得XY,其比例(p)在0.00和1.00之间,如下所示:

// this function gets the xy along a line
// that is proportionally (p) from 0.00 to 1.00
function getLineXY(startPt,endPt,p) {
    var dx = endPt.x-startPt.x;
    var dy = endPt.y-startPt.y;
    var X = startPt.x + dx*p;
    var Y = startPt.y + dy*p;
    return( {x:X,y:Y} );
}

这是一个循环,它将沿着线获得XY并检查xy处的像素颜色:

如果颜色不匹配,您可以使用setpixelcolour根据需要更改颜色。

for(var i=0;i<=1;i+=.005){

    // get the xy of a point along the line
    var pt=getLineXY(i);

    // get the rgb of that pixel at xy
    var ptColour=getpixelcolour(pt.x,pt.y);

    // if the strokeColor is not the ptColor, change the pixel's colour
    if(
        !(strokeColour.r ==  ptColor.r &&
          strokeColour.g ==  ptColor.g &&
          strokeColour.b ==  ptColor.b)
      )
      {
            setpixelcolour(pt.x,pt.y,newColor);
      }
}

这个过程中有一个“陷阱”:

Canvas Context会为笔画添加消除锯齿并填充它。

反锯齿会弄乱你的颜色比较。