Tuesday, January 5, 2010

Professional path smoothing in Javascript (think Inkscape)

Professional svg editors generally allow for smoothing freeform paths, and if a browser-based svg or animation editor ever wants to be competitive, it must have the same capability. Smooth paths are important not only because they look nicer, but also because any animation in which an object follows a path must be smooth. The open source Inkscape project, thankfully, smooths paths very well, and porting the code was fairly straightforward.

A freeform path is made up of line segments so small they don't appear to be lines, but instead make up a jagged curve. We plug this into our smoothing function, which returns points for cubic bezier curves. We can adjust the tolerance, which will influence the amount of smoothing that takes place and, therefore, the amount of path segments left over. In the demo, this value is hardcoded but can be changed easily by editing the source code.

Demo     Source code

1 comment: