Earcut - Polygon Triangulation

3.0.2 · active · verified Tue Apr 21

Earcut is a JavaScript library designed for fast and lightweight polygon triangulation, primarily optimized for WebGL applications. The current stable version is 3.0.2. It aims to provide real-time triangulation performance in browsers by prioritizing raw speed and simplicity over guaranteed correctness for highly degenerate or self-intersecting polygons. It implements a modified ear slicing algorithm using z-order curve hashing, capable of handling holes, twisted polygons, degeneracies, and self-intersections. While it doesn't guarantee perfectly correct triangulation for all edge cases, it typically produces acceptable results for practical datasets. It differentiates itself from alternatives by its significant speed advantage, as evidenced by benchmarks, and was originally developed for Mapbox GL. Earcut is a 2D algorithm, and for 3D inputs, it processes data as if projected onto the XY plane, ignoring the Z-component.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic polygon triangulation for both simple shapes and those with holes, including how 3D vertex data is handled (Z-component ignored).

import earcut from 'earcut';

// Triangulate a simple polygon (e.g., a square)
const vertices = [0, 0, 100, 0, 100, 100, 0, 100];
const simpleTriangles = earcut(vertices);
console.log('Simple Polygon Triangles:', simpleTriangles);
// Expected: [1,0,3, 2,1,3]

// Triangulate a polygon with a hole
const polygonWithHoleVertices = [
  0,0, 100,0, 100,100, 0,100,  // Outer ring (4 vertices)
  20,20, 80,20, 80,80, 20,80   // Inner ring (4 vertices)
];
const holeIndices = [4]; // The hole starts at index 4 (5th vertex)
const holedTriangles = earcut(polygonWithHoleVertices, holeIndices);
console.log('Polygon with Hole Triangles:', holedTriangles);
// Expected: [3,0,4, 5,4,0, 3,4,7, 5,0,1, 2,3,7, 6,5,1, 2,7,6, 6,1,2]

// Example with 3D coordinates (Z-component is ignored)
const vertices3D = [10,0,1, 0,50,2, 60,60,3, 70,10,4];
const triangles3D = earcut(vertices3D, null, 3); // dimensions = 3
console.log('3D Input (Z ignored) Triangles:', triangles3D);
// Expected: [1,0,3, 3,2,1]

view raw JSON →