Calculating Polygon Area
There is an algorithm to calculate polygon area:
function calcPolygonArea(vertices) {
var total = 0;
for (var i = 0, l = vertices.length; i < l; i++) {
var addX = vertices[i].x;
var addY = vertices[i == vertices.length - 1 ? 0 : i + 1].y;
var subX = vertices[i == vertices.length - 1 ? 0 : i + 1].x;
var subY = vertices[i].y;
total += (addX * addY * 0.5);
total -= (subX * subY * 0.5);
}
return Math.abs(total);
}
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.