Baking transforms into SVG Path Element commands

I have made a general SVG flattener flatten.js, that supports all shapes and path commands:
https://gist.github.com/timo22345/9413158

Basic usage: flatten(document.getElementById('svg'));

What it does: Flattens elements (converts elements to paths and flattens transformations).
If the argument element (whose id is above ‘svg’) has children, or it’s descendants has children,
these children elements are flattened also.

What can be flattened: entire SVG document, individual shapes (path, circle, ellipse etc.) and groups. Nested groups are handled automatically.

How about attributes? All attributes are copied. Only arguments that are not valid in path element, are dropped (eg. r, rx, ry, cx, cy), but they are not needed anymore. Also transform attribute is dropped, because transformations are flattened to path commands.

If you want to modify path coordinates using non-affine methods (eg. perspective distort),
you can convert all segments to cubic curves using:
flatten(document.getElementById('svg'), true);

There are also arguments ‘toAbsolute’ (convert coordinates to absolute) and ‘dec’,
number of digits after decimal separator.

Extreme path and shape tester: https://jsfiddle.net/fjm9423q/embedded/result/

Basic usage example: http://jsfiddle.net/nrjvmqur/embedded/result/

CONS: text element is not working. It could be my next goal.

Leave a Comment