如何在javascript中实现像素内形状算法

时间:2015-02-14 06:11:03

标签: javascript coordinates pixel shape

我现在正在编写一个脚本,用于检测像素是否在指定像素数组(形状边界)内,如图所示。

    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
    }

我认为在javaScript中可能会有更简单的实现,如果有的话请告诉我。
非常感谢。

Finding pixel within a shape

1 个答案:

答案 0 :(得分:1)

这个功能似乎可以解决问题:

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

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

示例:

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