Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which JavaScript library can do boolean operations with bezier curves?

Does a Javascript library exist which can perform boolean operations on paths (bezier curves)?

I know about Paper.js and Raphael.js, but both cannot perform these actions now.

like image 288
philipp Avatar asked Aug 09 '12 09:08

philipp


2 Answers

If you convert path to polygons (eg. using pathelement.getPointAtLength()), then you can use Javascript Clipper, which is a javascript port of popular Angus Johnson's Clipper Library.

This is an example of Difference, but also Union, Intersect and Xor are possible: Difference of polygons

The page of Javascript Clipper is here.

If getPointAtLength() gives too much points, Javascript Clipper has a function ClipperLib.Lighten(), which can reduce point count significantly.

The library supports also polygon offsetting. See the live demo.


EDIT: after testing I can confirm that pathelement.getPointAtLength() is best suitable for eg. hit testing, but not so good for polygonizing in this case, because it produces too few or too much points and doesn't take into account the curvature. It's the fact that tight curves need more points and loose curves fewer. Better is to convert all path segments to Cubic curves and use some adaptive algorithm for polygonizing curves. I have made some tests and may be soon can introduce a better way for polygonizing.

EDIT: I have managed to implement SVG path polygonizing function, which handles all kind of paths and also flattens transformations. After testing thousands randomly generated paths and transformations it seems to be reliable. Also all possible degenerate cases (where curves are collinear or some of the points are the same) are handled without issues. Although it is already many times faster and more precise than native getPointAtLength() while producing significantly fewer points, the process has room for speed improvements using eg. taxicab angles instead of atan2() and making the code fully Web Workers compatible by removing all DOM methods. I want to make it 100% bugfree before publishing it. It's ideal use case is eg. possibility to make boolean operations with generated polygons.

like image 98
Timo Kähkönen Avatar answered Oct 22 '22 01:10

Timo Kähkönen


Paper.js now has boolean operations in its core:

https://github.com/paperjs/paper.js/blob/master/src/path/PathItem.Boolean.js

And here you can see the operations in action:

http://assets.paperjs.org/boolean/

like image 7
Jürg Lehni Avatar answered Oct 22 '22 03:10

Jürg Lehni