I'm attempting to do some triangulation using the earcut library. I find the documentation on this library very thin, so hopefully someone has experience with the library and can help me out with this.
What I'm trying to achieve is to triangulate a polygon with an inner polygon which I want to threat as a hole. For this example I have a simple square polygon, and a smaller square polygon inside it.
The way I understood the earcut input format would handle it by using this array:
var a = [
[[0,100],[100,100],[100,0],[0,0]], //outer polygon
[[25,25],[75,25],[75,75],[25,75]] //hole
]
var toProcess = earcut.flatten(a);
var result = earcut(toProcess.vertices, toProcess.holes, toProcess.dimensions);
It all works and I get some triangles, but I would not expect them to cross the inner polygon.
When drawing the triangles returned on a canvas, this is my result:
I've tried googling a lot and did not find any good examples, also looked through earcuts tests on github, but wheren't able to get much from them either.
The example is pretty basic, so I guess someone with knowledge to this library would probably see what I'm doing wrong immediately.
From the github page it takes flat arrays so to get the triangulation for your example, with the second array pointing to the holes, all the verts from the first index of the second array to the end is the hole
var v = [[[0,100],[100,100],[100,0],[0,0]], //outer polygon
[[25,25],[75,25],[75,75],[25,75]]],
becomes
var flat = [0,100,100,100,100,0,0,0,25,25,75,25,75,75,25,75]
| | | | | | | |
// vert index 0 1 2 3 4 5 6 7
Verts index is array index / dimensions (2d dimensions = 2)
then the call
var poly = earcut(flat,[4]); //points to the hole starting at the 4th vert to the 7th
For two holes
var flat = [0,100,100,100,100,0,0,0,25,25,75,25,75,75,25,75, 2,2,7,2,7,7,2,7]
var poly = earcut(flat,[4,8]); // creates two holes
// using verts 4,5,6,7 first hole
// uning verts 8,9,10,11 second hole
UPDATE
I think the problem is when you draw the polys you are getting the indexes incorrect.
To draw the polys
var v = toProcess.vertices
for(var i = 0; i < result.length; i += 3){
ctx.beginPath();
ctx.moveTo(v[result[i]*2],v[result[i]*2+1])
ctx.lineTo(v[result[i+1]*2],v[result[i+1]*2+1])
ctx.lineTo(v[result[i+2]*2],v[result[i+2]*2+1])
ctx.closePath();
ctx.stroke();
}