Danya Lette

Delaunay Triangulation in JS

javascript math svg

 

My initial goal was to make a dynamically generated triangle pattern for a site, like so:

The pattern.

That site will generate a new pattern on each visit.

Here you see a set of points, randomly generated, that has been triangulated. In other words, every generated point has become the vertex of a triangle and all triangles are non-overlapping.

The demo.

In the demo, drag points to see the triangulation recalculate.

This geometric solution to that problem is called Delaunay Triangulation.

Having made the pattern generator, I wanted to play around a bit more so I added support for dragging the points/vertices, recalculating the Delaunay Triangulation, and generating a fresh batch of points of a variable number.

If you dragged some points around in the demo and you found yourself wondering about the recalculations, you might be interested to know that, as per wikipedia, “Delaunay triangulations maximize the minimum angle of all the angles of the triangles in the triangulation; they tend to avoid skinny triangles.”

Factoids:

  1. The demo generates points that have a normal distribution, with a mean of width/2 and a std deviation of width/5, so that the generated points cluster around the center – I find that a bit more aesthetically pleasing.

  2. I’m using Raphael.js to ease the SVG JS process.

  3. I’m using the stroke-dashoffset trick for the initial line-drawing animation.

  4. The calculation of the Delaunay Triangulation is accomplished by this Javascript port of this C implementation.