So I've gotten this code in javascript to calculate irregular polygon area from the net.
function polygonArea(X, Y, numPoints)
{
area = 0; // Accumulates area in the loop
j = numPoints-1; // The last vertex is the 'previous' one to the first
for (i=0; i<numPoints; i++)
{ area = area + (X[j]+X[i]) * (Y[j]-Y[i]);
j = i; //j is previous vertex to i
}
return area/2;
}
var xPts = [3, 3, 2, 2, 3, 3, 6, 6, 9, 9, 4, 4 ];
var yPts = [2, 4, 4, 5, 5, 6, 6, 5, 5, 3, 3, 2];
var a = polygonArea(xPts, yPts, 4);
alert("Area = " + a);
The results seems to be correct. if the vertex traced by clock-wise direction, it will shows positive results however it will become negative if i traced vertex in anti clockwise direction. Why is that so?
How does this algorithm work? i really want to know what is the mathematical explanation behind it, because i am still having a hard time to understand the explanation on the net.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…