Ponto Dentro Do Polígono //Repositório JavaScript

Descrição

Verifica se um ponto está dentro de um polígono. Adaptado de: [http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html]
Criado: 2008.03.14

Código (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/is-point-in-poly [rev. #0]

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

Exemplo (Exemplo)

Click inside and outside of the polygon.

<script type="text/javascript" src="/js/graphical-plotter.js"></script>
<script type="text/javascript">
//<![CDATA[

var length = 50,
points = [
    {x: 0, y: 0},
    {x: 0, y: length},
    {x: length, y: 10},
    {x: -length, y: -10},
    {x: 0, y: -length},
    {x: 0, y: 0}
];

var canvas = new Canvas;
canvas.pen.color = "#f00";
canvas.pixelSize = 5;

canvas.moveTo(length, length);
for(var i = points.length; i--; canvas.lineTo(length + points[i].x, length + points[i].y));

document.onclick = function(e){
    function getMouse(e){
        var w = window, b = document.body;
        return {x: e.clientX + (w.scrollX || b.scrollLeft || b.parentNode.scrollLeft || 0),
        y: e.clientY + (w.scrollY || b.scrollTop || b.parentNode.scrollTop || 0)};
    }
    var m = getMouse(e || event);
    alert(isPointInPoly(points, {x: m.x / canvas.pixelSize - length, y: m.y / canvas.pixelSize - length}) ? "In" : "Out");
}

//]]>
</script>

Ajuda

isPointInPoly(polygon: Array, point: Object): Boolean
Verifica se o ponto está dentro do polígono.
polygon
array de pontos, cada elemento deve ser um objeto contendo duas propriedades (x e y)
point
ponto, objeto contendo duas propriedades (x e y)

Ranque (Votos: 1574)

4.96