Intersecting Arbitrary Polygons with Raphaël.js

3D printers suck. Which is to say that if you want to print something on a 3D printer, you’re almost pulling the oil out of the ground yourself, they’re so dumb. So when you want to let someone design a 2D object (a snowflake) in a web browser and then have you print it and send it to them and you find out that All You Need To Do™ is draw in SVG, convert to DWG, extrude it and print it: no. You’ve got to flatten that SVG because there’s actually hundreds of triangles there and if you ask your printer to print hundreds of triangles it’ll just throw it’s arms up and continue to sit there contemplating the universe and its own existence. Because it’s so dumb. I’ve never had more respect for printers that just put ink on paper. You want how many words? Done. Collated.

I felt really good when I finally figured out what to search for and found the Weiler–Atherton clipping algorithm and Efficient Clipping of Aribitrary Polygons (with code!). I felt really silly (not quite throwing-my-hands-up dumb, though) when I found PolyClip.jsx on my own computer. It’s an Adobe port of the aforementioned article’s C code to ExtendScript (I must note that the wizards at Adobe figured the default font for code comments in ExtendScript Toolkit should be Comic Sans) which might as well be the code I wanted to do myself. So:

Here’s a well-commented port to JavaScript as a Raphaël.js plugin. There’s some utility functions for vector geometry and the fun stuff for intersecting elements and sets of elements. It works fine for convex and concave polygons, although more complex concave polygons seem to throw it off. Self-intersecting polygons probably won’t work. These are faults of my own programming and not the algorithms or sources by any means, but I plan to address this and generalize the plugin beyond my own uses (lots of triangles) over time.

Get it on Github.