0

我想要一个检查画布中笔画和像素颜色的函数。如果画布中像素的颜色和描边的颜色相同,则不要改变描边的颜色。我已经尝试了下面的功能,但它不起作用。知道如何实现这一目标吗?谢谢

//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]
    };
}
4

1 回答 1

0

Here’s how to change the pixel color along a line based on the stroke and existing pixels.

First you need to get the XY coordinates along that the line from start to end:

Given:

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

You can get an XY along that line which is proportionally (p) between 0.00 and 1.00 like this:

// 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} );
}

This is a loop that will get XY’s along the line and examine the pixel color at that xy:

If the colors do not match, you can use your setpixelcolour to change it as you desire.

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);
      }
}

One “gotcha” in this process:

Canvas Context will add anti-aliasing to the strokes and fills it draws.

That anti-aliasing will mess up your color comparisons.

于 2013-07-23T16:47:56.213 回答