I found some people are getting stuck with understanding the Shoelace Formula, which is the area formula for polygons including irregular ones.
In this article, I would like to try to explain the formula intuitively using the visualizer I made.
To note first, we assume
- we consider only polygons in 2D.
- the edges of polygon are not self-intersecting.
- the number of vertices of polygon is n.
- the coordinates of the vertices are in counter-clockwise order and represented as P1(x1, y1), …, P2(xn, yn), Pn + 1(xn + 1, yn + 1), where xn + 1 = x1, yn + 1 = y1 for simplicity.
The above equation (Shorlace Formula) can be transformed into the sum of trapezoids as below: $$ S = \sum_{i = 1}^{n} \frac{1}{2}(x_{i} - x_{i + 1})(y_{i} + y_{i + 1}) $$
Proof. $$ \begin{align}&{} \sum_{k = 1}^{N} \frac {1}{2} (y_k+y_{k+1})(x_k - x_{k+1}) \\ &=\frac {1}{2} \sum_{k = 1}^{N} (x_ky_{k+1}- x_{k+1}y_k + x_ky_k - x_{k+1}y_{k+1}) \\ &=\frac {1}{2} \sum_{k = 1}^{N} (x_ky_{k+1}- x_{k+1}y_k) + \frac{1}{2}\sum_{k = 1}^{N}( x_ky_k - x_{k+1}y_{k+1}) \\ &=\frac {1}{2} \sum_{k = 1}^{N} (x_ky_{k+1}- x_{k+1}y_k) \end{align} $$ The term inside the sigma corresponds to a signed area of trapezoid consisting of (xi, 0), (xi + 1, 0), Pi + 1, Pi
I assume you know the area formula for trapezoids :) Also, we can see the formula also works correctly with negative coordinates.
Anyway, I made the visualizer with JS to help you understand the area calculation, so please try this. I hope this may help you understand the formula more intuitively.
Source
You can check my JS source and an example html on Gist or JSFiddle.
Usage
Choose the vertices of polygon and click Visualize!
. You can understand the area calculation in 2 ways as I explained - in the triangle way and the trapezoid way. Select Triangle
or Trapezoid
from the pull-down menu. Also, the coordinates of vertices will be shown in the left side area.
blue : +positive area, red : -negative area
The points of polygon should be in counter-clockwise order.