Search code examples
javascriptcoordinatespixelshapes

How to implement pixel Within shape algorithm in javascript


I am now writing a script that detect whether a pixel is within specified pixel array (shape boundary) as in figure.

    var shape=[
         {x:3,y:1},
         {x:4,y:1},
         {x:5,y:1},
         {x:6,y:1},
         {x:7,y:1},
         {x:7,y:2},
         {x:6,y:3},
         {x:5,y:4},
         {x:6,y:5},
         {x:7,y:6},
         {x:8,y:6},
         {x:8,y:5},
         {x:8,y:4},
         {x:8,y:3},
         {x:9,y:2},
         {x:9,y:1}
       ];

    var pixel={x:3,y:3}; //dynamic coordinate value from mouse event
   for(var i in shape){
         //check pixel whether within shape or outside
    }

I think there may be simpler implementation in javaScript, please let me know if any.
Thanks alot.

Finding pixel within a shape


Solution

  • This function seems to do the trick:

    function isPointInPoly(poly, pt){
        for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
            ((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
            && (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
            && (c = !c);
        return c;
    }
    

    From: http://jsfromhell.com/math/is-point-in-poly

    Example:

    var shape=[
        {x:3,y:1},
        {x:4,y:1},
        {x:5,y:1},
        {x:6,y:1},
        {x:7,y:1},
        {x:7,y:2},
        {x:6,y:3},
        {x:5,y:4},
        {x:6,y:5},
        {x:7,y:6},
        {x:8,y:6},
        {x:8,y:5},
        {x:8,y:4},
        {x:8,y:3},
        {x:9,y:2},
        {x:9,y:1}
    ];
    
    var p1 = {x:1, y:2};
    var p2 = {x:6, y:3};
    var p1in = isPointInPoly(shape, p1);
    var p2in = isPointInPoly(shape, p2);
    alert(p1in + ', ' + p2in);
    
    function isPointInPoly(poly, pt){
        for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
            ((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
            && (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
            && (c = !c);
        return c;
    }