Visualizing Shoelace Formula, the formula for area of polygons

Published on December 9, 2020
Tags: computer-science, math

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.
then, we can calculate the area of polygon S by the great Shoelace formula: $$ S = \sum_{i = 1}^{n} \frac{1}{2}(x_{i} y_{i + 1} - x_{i + 1} y_{i}) $$ The most difficult part of understanding this is the fact that the term inside the sigma can be negative, which enables us to calculate areas of irregular polygons. As the Wikipedia explains it well, you can interpret the term as the signed area of triangle OPiPi + 1. By the way, you can understand the formula in another way - to interpret it as the sum of trapezoids. Let me explain this a little.

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.





Points: