Earcut Triangles

I am using earcut with the hope of generating correct triangle coordinates for an svg path.

This is what I tried. But I am not sure if I am doing it correctly (probably not). It generates the coordinates for triangles but they seem to be way off.

How do I get the correct triangle coordinates for any given svg path using this library or generate n triangles for a given path using any other library?

Thank you in advance.

No, it returns point indices for triangles. You may want to take a closer look at the documentation which also contains examples: GitHub - mapbox/earcut: The fastest and smallest JavaScript polygon triangulation library for your WebGL apps


By the way: In Observable you can simply return a value from a cell to display its output. Instead of writing

{
  // ...
  console.log(triangles);
}

try

{
  // ...
  return triangles;
}

instead.

1 Like

To add to what @mootari says, in earcut you have to specify holes separately. In the case of this big O, there is a larger polygon (outer circumference), with one hole consisting of the inner circumference.

1 Like

I was hoping earcut can generate triangle points for any given path without requiring author to fulfill the path hole. If that is the case, I don’t see any advantage in using this. Also, as far as triangle coordinates are concerned, I will stick d3.delaunay. I am so used to it.

Earcut is optimized for speed and shines when you need to triangulate lots of points, but that comes at a cost. E.g. it doesn’t handle collinear points well.

However, returning indices is also a common pattern since any data beyond a few points would cause memory usage to explode if you returned the actual coordinates, and maybe more importantly it’s also a lot slower.