Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  133] [ 7]  / answers: 1 / hits: 17335  / 11 Years ago, mon, april 29, 2013, 12:00:00

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.


More From » math

 Answers
127

Imagine drawing horizontal lines from each vertex to the Y axis; for each edge, this will describe a trapezoid:



Y-axis
^
|
|--------o (X[j], Y[j])
|
|
|
|------------o (X[i], Y[i])
|
+----------------------------> X-axis


The formula (X[j]+X[i]) * (Y[j]-Y[i]) in the inner loop computes twice the area of this trapezoid if Y[i] <= Y[j], or negative twice the area if Y[i] >= Y[j].



For a closed polygon, this naturally subtracts the area to the left of the upgoing edges from the area to the left of the downgoing edges. If the polygon is clockwise, this neatly cuts out the exact (doubled) area of the polygon; if counterclockwise, you get the negative (doubled) area.



To compute the area of a given polygon,



Y-axis
^
|
| o------o
| |
| |
| o
| o
| /
| /
| /
| /
| o
|
+-------------------------> X-axis


take the downgoing area:



Y-axis
^
|
|--------o------o
|
|
| o
| o
| /
| /
| /
| /
|--------------o
|
+-------------------------> X-axis


minus the upgoing area:



Y-axis
^
|
|--------o o
| |
| |
| o
| o
|
|
|
|
|--------------o
|
+-------------------------> X-axis


Although the above example uses a convex polygon, this area computation is correct for arbitrary polygons, regardless of how many up- and down- paths they may have.


[#78529] Sunday, April 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brookelynshaem

Total Points: 468
Total Questions: 98
Total Answers: 101

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;