Polygon area (Javascript)

Download Typescript (Visual Studio 2015 project) source code (118kb)





Description

This tiny application allows to specify the vertices of a polygon and to calculate its area.
Note that it must be a simple polygon to work correctly, without holes and overlaps.

Usage information


Notes for polygon area calculation

The Gauss's area formula is used to calculate the area of the simple polygon.
The main idea and steps are as follows:

So let's do an example step-by-step:

Image of triangle whose area to calculate

In this example we use the triangle on the left. Note that the vertices are numbered and thus the triangle is defined in counter-clockwise order.

First triangle area calculation step

The first triangle is formed by vertice 1 (130, 45) and vertics 4 (310 270) with the origin.
Remember the cross product is calculated as ax * by - ay * bx (where a and b are two vectors). We always use the vectors from the origin to the current two vertices. The cross product here is:
130 * 270 - 45 * 310 = 21150.
Note that the area of the triangle is half the cross product, thus 10575.

Second triangle area calculation step

Next triangle is formed by vertice 2 (40, 250) and vertice 1 (130, 45) with the origin.

So the cross product is:
40 * 45 - 250 * 130 = -30700.
Half of -30700 is -15350.

Total area of the example triangle until now is:
10575 - 15350 = -4775

Third triangle area calculation step

Next triangle is formed by vertice 3 (110, 195) and vertice 2 (40, 250) with the origin.

So the cross product is:
110 * 250 - 195 * 40 = 19700.
Half of 19700 is 9850.

Total area of the example triangle until now is:
10575 - 15850 + 9850 = 5075

Fourth triangle area calculation step

Last triangle is formed by vertics 4 (310 270) and vertice 3 (110, 195) with the origin.

So the cross product is:
310 * 195 - 270 * 110 = 30750.
Half of 30750 is 15375.

Total area of the example triangle until now is:
10575 - 15850 + 9850 + 15375 = 20450

Overlayed triangle steps to form the whole triangle area

Summarized, the area of the rot-dotted triangle is included by the steps of the green, blue and purple triangles. However, it is competely subtracted in the step with the orange triangle: the sign is of the cross product is the opposite because of the direction and order of the vertices, so the remaining calculated area matches exactly the area of the target triangle.

Hope you liked it!

Sunshine2k, July 2k17



History

2016/07/14: Initial release.


References

[1] Gauss's area formula @ Wikipedia