svg-path-commander 2.3.3 → 2.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,41 +1,43 @@
1
- # SVGPathCommander
2
-
3
- [![Coverage Status](https://coveralls.io/repos/github/thednp/svg-path-commander/badge.svg)](https://coveralls.io/github/thednp/svg-path-commander)
4
- [![ci](https://github.com/thednp/svg-path-commander/actions/workflows/ci.yml/badge.svg)](https://github.com/thednp/svg-path-commander/actions/workflows/ci.yml)
5
- [![NPM Version](https://img.shields.io/npm/v/svg-path-commander.svg)](https://www.npmjs.com/package/svg-path-commander)
6
- [![JSR Version](https://img.shields.io/jsr/v/@thednp/svg-path-commander.svg)](https://jsr.io/@thednp/svg-path-commander)
7
- [![NPM Downloads](https://img.shields.io/npm/dm/svg-path-commander.svg)](http://npm-stat.com/charts.html?svg-path-commander)
8
- [![jsDeliver](https://img.shields.io/jsdelivr/npm/hw/svg-path-commander)](https://www.jsdelivr.com/package/npm/svg-path-commander)
9
-
10
-
11
- ![image](./docs/assets/SVGPathCommander.svg)
12
-
13
- A modern set of Typescript tools for manipulating the `d` (description) attribute for *SVGPathElement* items. The library is implementing modern JavaScript API to produce reusable path strings with lossless quality. In addition, you also have a powerful tool to convert other SVG shapes like `<circle>` or `<rect>` to `<path>`.
14
-
15
-
16
- While you may find familiar tools inside, this library brings ***new additions***:
17
- * the build in `getBBox`, `getPointAtLength` and `getTotalLength` are more reliable and much more accurate than the native methods, not to mention their high [performance](https://github.com/thednp/svg-path-commander/issues/44) ratings;
18
- * thanks to the community contributions we've implemented useful tools like `getPropertiesAtLength`, `getSegmentOfPoint` or `isPointInStroke`;
19
- * a tool that can *reverse path draw direction* without altering path commands, even with specific shorthand path commands;
20
- * a unique tool that can *reverse path draw direction* for path strings with only 'C' path commands;
21
- * a new and unique tool to *apply transform functions to path commands* via the modern *DOMMatrix* API.
22
-
23
- **The key differences with other libraries**:
24
- * Typescript sourced with modernized codebase, all inherited codebase has been modernized as well;
25
- * along with the modern codebase, the library also comes with strong TypeScript definitions;
26
- * this library can create 3D to 2D projections, making your SVGs look like 3D but in the SVG coordinate system;
27
- * you can use this library in both web apps and Node.js, you are not restricted to a single environment;
28
- * path command transformations are all consistent with the SVG coordinates system, where others compute transform origin only for rotation transformation.
29
-
30
- **SVGPathCommander** can use the [DOMMatrix API](https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrix) for *SVGPathElement* path command transformation and implements a very fast and modernized [DOMMatrix shim](https://github.com/thednp/dommatrix).
31
- There are a couple of good reasons for this implementation:
32
- * *WebKitCSSMatrix* and *SVGMatrix* APIs are slowly pushed away by DOMMatrix, the green light for new and modern implementations;
33
- * we can actually apply a [3D transformation](https://github.com/ndebeiss/svg3d) matrix to SVG path commands, by calculating a 2D projection of the actual shape in 3D coordinates;
34
- * when most tools available will be rendered absolete, we are ready for new challenges.
35
-
36
- This library is available on [CDN](https://www.jsdelivr.com/package/npm/svg-path-commander), [npm](https://www.npmjs.com/package/svg-path-commander) and [JSR](https://jsr.io/@thednp/svg-path-commander).
37
-
1
+ # SVGPathCommander
2
+
3
+ [![Coverage Status](https://coveralls.io/repos/github/thednp/svg-path-commander/badge.svg)](https://coveralls.io/github/thednp/svg-path-commander)
4
+ [![ci](https://github.com/thednp/svg-path-commander/actions/workflows/ci.yml/badge.svg)](https://github.com/thednp/svg-path-commander/actions/workflows/ci.yml)
5
+ [![NPM Version](https://img.shields.io/npm/v/svg-path-commander.svg)](https://www.npmjs.com/package/svg-path-commander)
6
+ [![JSR Version](https://img.shields.io/jsr/v/@thednp/svg-path-commander.svg)](https://jsr.io/@thednp/svg-path-commander)
7
+ [![NPM Downloads](https://img.shields.io/npm/dm/svg-path-commander.svg)](http://npm-stat.com/charts.html?svg-path-commander)
8
+ [![jsDeliver](https://img.shields.io/jsdelivr/npm/hw/svg-path-commander)](https://www.jsdelivr.com/package/npm/svg-path-commander)
9
+
10
+ ![image](./docs/assets/SVGPathCommander.svg)
11
+
12
+ A modern set of Typescript tools for manipulating the `d` (description) attribute for _SVGPathElement_ items. The library is implementing modern JavaScript API to produce reusable path strings with lossless quality. In addition, you also have a powerful tool to convert other SVG shapes like `<circle>` or `<rect>` to `<path>`.
13
+
14
+ While you may find familiar tools inside, this library brings _**new additions**_:
15
+
16
+ - the build in `getBBox`, `getPointAtLength` and `getTotalLength` are more reliable and much more accurate than the native methods, not to mention their high [performance](https://github.com/thednp/svg-path-commander/issues/44) ratings;
17
+ - thanks to the community contributions we've implemented useful tools like `getPropertiesAtLength`, `getSegmentOfPoint` or `isPointInStroke`;
18
+ - a tool that can _reverse path draw direction_ without altering path commands, even with specific shorthand path commands;
19
+ - a unique tool that can _reverse path draw direction_ for path strings with only 'C' path commands;
20
+ - a new and unique tool to _apply transform functions to path commands_ via the modern _DOMMatrix_ API.
21
+
22
+ **The key differences with other libraries**:
23
+
24
+ - Typescript sourced with modernized codebase, all inherited codebase has been modernized as well;
25
+ - along with the modern codebase, the library also comes with strong TypeScript definitions;
26
+ - this library can create 3D to 2D projections, making your SVGs look like 3D but in the SVG coordinate system;
27
+ - you can use this library in both web apps and Node.js, you are not restricted to a single environment;
28
+ - path command transformations are all consistent with the SVG coordinates system, where others compute transform origin only for rotation transformation.
29
+
30
+ **SVGPathCommander** can use the [DOMMatrix API](https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrix) for _SVGPathElement_ path command transformation and implements a very fast and modernized [DOMMatrix shim](https://github.com/thednp/dommatrix).
31
+ There are a couple of good reasons for this implementation:
32
+
33
+ - _WebKitCSSMatrix_ and _SVGMatrix_ APIs are slowly pushed away by DOMMatrix, the green light for new and modern implementations;
34
+ - we can actually apply a [3D transformation](https://github.com/ndebeiss/svg3d) matrix to SVG path commands, by calculating a 2D projection of the actual shape in 3D coordinates;
35
+ - when most tools available will be rendered absolete, we are ready for new challenges.
36
+
37
+ This library is available on [CDN](https://www.jsdelivr.com/package/npm/svg-path-commander), [npm](https://www.npmjs.com/package/svg-path-commander) and [JSR](https://jsr.io/@thednp/svg-path-commander).
38
+
38
39
  <!-- BENCH:start -->
40
+
39
41
  # Performance
40
42
 
41
43
  A comparison of **SVGPathCommander** with the [SvgPath](https://github.com/fontello/svgpath) library v2.6.0 and its [svg-path-bbox](https://github.com/fontello/svg-path-bbox) helper v2.1.0, run with `pnpm bench` against a sample path with `11650` path segments. All values are in **milliseconds**, reported as `avg / best` over 10 runs after 3 warmups; lower is better. The `vs svgpath` column is the `avg` ratio of SVGPathCommander to svgpath.
@@ -44,314 +46,341 @@ A comparison of **SVGPathCommander** with the [SvgPath](https://github.com/fonte
44
46
 
45
47
  ## Static methods
46
48
 
47
- | Operation | SVGPathCommander (static) | svgpath | vs svgpath |
48
- | --- | --- | --- | --- |
49
- | parse | **7.4 / 7** | 9.7 / 9 | **0.8x** |
50
- | bbox | **5.2 / 4** | 6.8 / 6 | **0.8x** |
51
- | transform2d | 1.7 / 1 | 1.2 / 1 | 1.4x |
52
- | transform3d | **14.3 / 11** | n/a | n/a |
53
- | string | 6.2 / 5 | 5 / 5 | 1.2x |
49
+ | Operation | SVGPathCommander (static) | svgpath | vs svgpath |
50
+ | ----------- | ------------------------- | ------- | ---------- |
51
+ | parse | **8 / 7** | 9.4 / 9 | **0.9x** |
52
+ | bbox | **5.3 / 4** | 6.8 / 6 | **0.8x** |
53
+ | transform2d | **3.4 / 1** | 3.5 / 1 | **1x** |
54
+ | transform3d | **12.5 / 11** | n/a | n/a |
55
+ | string | 3.6 / 3 | 3.5 / 3 | 1x |
54
56
 
55
57
  ## Instance methods
56
58
 
57
- | Operation | SVGPathCommander (instance) | svgpath | vs svgpath |
58
- | --- | --- | --- | --- |
59
- | parse | **7.3 / 7** | 9.7 / 9 | **0.8x** |
60
- | bbox | **5 / 4** | 6.8 / 6 | **0.7x** |
61
- | transform2d | 1.3 / 0 | 1.2 / 1 | 1.1x |
62
- | transform3d | **8.4 / 7** | n/a | n/a |
63
- | string | 5.9 / 5 | 5 / 5 | 1.2x |
64
-
65
- Last benchmark run on `2026-08-05`. Generated by [`scripts/bench.js`](scripts/bench.js); update with `pnpm bench`.
66
- <!-- BENCH:end -->
67
-
68
-
69
- # Install
70
-
71
- ```sh
72
- npm install svg-path-commander
73
- # or pnpm add svg-path-commander
74
- # or bun add svg-path-commander
75
- # or deno add npm:svg-path-commander
76
- # or deno add jsr:@thednp/svg-path-commander
77
- # or npx jsr add @thednp/svg-path-commander
78
- ```
79
-
80
- In a Deno project, install from [JSR](https://jsr.io/@thednp/svg-path-commander) and import the raw TypeScript source directly:
81
-
82
- ```ts
83
- import SVGPathCommander from "jsr:@thednp/svg-path-commander";
84
- ```
85
-
86
-
87
- # CDN
88
- Version 2.2.0+
89
- ```html
90
- <script src="https://cdn.jsdelivr.net/npm/svg-path-commander/dist/index.min.js">
91
- ```
92
-
93
- Versions before 2.2.0
94
- ```html
95
- <script src="https://cdn.jsdelivr.net/npm/svg-path-commander/dist/svg-path-commander.js">
96
- ```
97
-
98
- # Quick Guide
99
-
100
- Flip a path on the X axis:
101
- ```js
102
- import SVGPathCommander from 'svg-path-commander';
103
-
104
- const path = 'M0 0L100 0L50 100';
105
-
106
- const flippedPathString = new SVGPathCommander(path).flipX().toString();
107
- // result => 'M0 100h100L50 0'
108
- ```
109
-
110
- Optimize a path string by using the `round` option, to round numbers to 2 decimals and finding shorthand where possible:
111
- ```js
112
- const optimizedPathString = new SVGPathCommander(path, {round: 2}).optimize().toString();
113
- ```
114
-
115
- Or why not apply a **2D transformation** and even a **3D transformation**:
116
- ```js
117
- // a transform object
118
- const transform = {
119
- translate: 15, // X axis translation
120
- rotate: 15, // Z axis rotation
121
- scale: 0.75, // uniform scale on X, Y, Z axis
122
- skew: 15, // skew 15deg on the X axis
123
- origin: [15, 0] // if not specified, it will use the default origin value [0, 0]
124
- }
125
- const transformed2DPathString = new SVGPathCommander(path).transform(transform).toString();
126
-
127
- // apply a 3D transformation
128
- const transform = {
129
- translate: [15, 15, 15], // `[15, 15]` would apply a 2D translation, and only `15` for X axis translation
130
- rotate: [15, 15, 15], // or only "15" for 2D rotation on Z axis
131
- scale: [0.7, 0.75, 0.8], // or only "0.7" for 2D scale on all X, Y, Z axis
132
- skew: [15, 15], // or only "15" for the X axis
133
- origin: [15, 15, 15] // full `transform-origin` for a typical 3D transformation
134
- }
135
- const transformed3DPathString = new SVGPathCommander(path).transform(transform).toString();
136
- ```
137
-
138
- Access the `bbox` instance property to apply a consistent `transform-origin`:
139
- ```js
140
- // apply a 3D transformation with a consistent origin
141
- const transformed3DPath = new SVGPathCommander(path);
142
- const { cx, cy, cz } = transformed3DPath.bbox;
143
- const transform = {
144
- translate: [15, 15, 15], // `[15, 15]` would apply a 2D translation, and only `15` for X axis translation
145
- rotate: [15, 15, 15], // or only "15" for 2D rotation on Z axis
146
- scale: [0.7, 0.75, 0.8], // or only "0.7" for 2D scale on all X, Y, Z axis
147
- skew: [15, 15], // or only "15" for the X axis
148
- origin: [cx, cy, cz] // the origin
149
- }
150
- const transformed3DPathString = transformed3DPath.transform(transform).toString();
151
- ```
152
-
153
- SVGPathCommander comes with a full range of additional static methods, here's how to normalize a path:
154
- ```js
155
- const path = 'M0 0 H50';
156
-
157
- const normalizedPath = SVGPathCommander.normalizePath(path);
158
- // result => [['M', 0, 0], ['L', 50, 0]]
159
- ```
160
-
161
- Reverse a path:
162
- ```js
163
- const path = SVGPathCommander.parsePathString('M0 0 H50');
164
-
165
- const reversedPath = SVGPathCommander.reversePath(path);
166
- // result => [['M', 50, 0], ['H', 0]]
167
- ```
168
-
169
- Export to string:
170
- ```js
171
- const myPathString = SVGPathCommander.pathToString([['M', 0, 0], ['L', 50, 0]]);
172
- // result => 'M0 0 L50 0'
173
- ```
174
-
175
- Check a path string validity:
176
- ```js
177
- SVGPathCommander.isValidPath(path);
178
- // result => boolean
179
- ```
180
-
181
- Check if path is a certain kind of `PathArray`:
182
- ```js
183
- SVGPathCommander.isAbsoluteArray([['M', 0, 0], ['L', 50, 0]]);
184
- // result => true
185
- ```
186
-
187
- Use treeshake and create a custom function to apply a 3D transformation using static methods:
188
- ```ts
189
- import { parsePathString, getPathBBox, transformPath, pathToString } from 'svg-path-commander';
190
-
191
- function myTransformFn(pathInput: string | PathArray, transformObject: TransformObject) {
192
- const path = parsePathString(pathInput);
193
- const { cx, cy, cz } = getPathBBox(path);
194
-
195
- return pathToString(
196
- transformPath(path, {
197
- ...transformObject, origin: [cx, cy, cz]
198
- })
199
- )
200
- }
201
- ```
202
- In extreme cases where performance is paramount, you can consider the parent SVG `viewBox` attribute to extract a bounding box required for a consistent transform origin.
203
-
204
- ```ts
205
- // const svgViewBox = document.getElementById('my-svg').getAttribute('viewBox');
206
- const viewBox = '0 0 24 24';
207
-
208
- const [x, y, width, height] = viewBox.split(/\s/).map(Number);
209
- const origin = [
210
- x + width / 2, // CX
211
- y + height / 2, // CY
212
- Math.max(width, height) + Math.min(width, height) / 2, // CZ
213
- ];
214
-
215
- // use this origin for your shape transformation
216
- const myNewString = new SVGPathCommander('M0 0 H50')
217
- .transform({ rotate: [35, 0, 0], origin })
218
- .toString();
219
- ```
220
-
221
-
222
- Convert a shape to `<path>` and transfer all non-specific attributes
223
- ```js
224
- const myCircle = document.getElementById('myCircle');
225
- SVGPathCommander.shapeToPath(myCircle, true);
226
- ```
227
-
228
- Alternatively you can create `<path>` from specific attributes:
229
- ```js
230
- const myRectAttr = {
231
- type: 'rect',
232
- x: 25,
233
- y: 25,
234
- width: 50,
235
- height: 50,
236
- rx: 5
237
- };
238
-
239
- const myRectPath = SVGPathCommander.shapeToPath(myRectAttr);
240
- document.getElementById('mySVG').append(myRectPath);
241
- ```
242
- Server-side using `jsdom`:
243
- ```js
244
- const { document } = new JSDOM(
245
- `<html>
246
- <head></head>
247
- <body>
248
- <svg id="mySVG" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
249
- <rect id="myRect" x="0" width="100" height="100" rx="15" />
250
- </svg>
251
- </body>
252
- </html>`,
253
- {
254
- pretendToBeVisual: true,
255
- }
256
- ).window;
257
-
258
- const myRect = document.getElementById('myRect');
259
- SVGPathCommander.shapeToPath(myRect, true, document);
260
- ```
261
-
262
- Get the path length:
263
- ```js
264
- const myPathLength = SVGPathCommander.getTotalLength('M0 0L50 0L25 50z');
265
- // result => 161.80339887498948
266
- ```
267
-
268
- Get a point along the path:
269
- ```js
270
- const myPoint = SVGPathCommander.getPointAtLength('M0 0L50 0L25 50z', 85);
271
- // result => {x: 34.34752415750147, y: 31.304951684997057}
272
- ```
273
-
274
- Get the path bounding box:
275
- ```js
276
- const myPathBBox = SVGPathCommander.getPathBBox('M0 0L50 0L25 50z');
277
- // result => {width: 50, height: 50, x: 0, y: 0, x2: 50, y2: 50, cx: 25, cy: 25, cz: 75}
278
- ```
279
-
280
- Find intersection points between two paths:
281
- ```js
282
- const count = SVGPathCommander.pathsIntersection(
283
- 'M0 50C0 0,100 0,100 50',
284
- 'M50 0C100 0,100 100,50 100',
285
- true
286
- );
287
- // result => 1
288
-
289
- const points = SVGPathCommander.pathsIntersection(
290
- 'M0 50C0 0,100 0,100 50',
291
- 'M50 0C100 0,100 100,50 100',
292
- false
293
- );
294
- // result => [{ x: 50, y: 25, t1: 0.5, t2: 0.5 }]
295
- ```
296
-
297
- Equalize two paths for morphing (single subpath):
298
- ```js
299
- const [eq1, eq2] = SVGPathCommander.equalizeSegments(
300
- 'M0 0L100 0L50 100Z',
301
- 'M0 0L100 0L100 100L0 100Z'
302
- );
303
- // eq1.length === eq2.length — ready for morphing
304
- ```
305
-
306
- Equalize two paths for morphing (single or multi subpath):
307
- ```js
308
- const [eq1, eq2] = SVGPathCommander.equalizePaths(
309
- 'M0 0L100 0L50 100Z',
310
- 'M0 0L100 0L100 100L0 100Z',
311
- { close: true }
312
- );
313
- // Both paths now have the same number of segments
314
- ```
315
-
316
- # WIKI
317
- For developer guidelines, and a complete list of static methods, head over to the [`wiki/`](wiki/) folder in this repository.
318
-
319
-
320
- # What Is It For?
321
-
322
- * converting and optimizing *SVGPathElement* for use in third party application; our [KUTE.js](https://github.com/thednp/kute.js) animation engine is using it to process *SVGPathElement* coordinates for [SVG morphing](https://thednp.github.io/kute.js/svgMorph.html) and [SVG cubic morphing](https://thednp.github.io/kute.js/svgCubicMorph.html);
323
- * animators that work with SVGs and need tools for performing specific path command processing;
324
- * front-end developers looking to spice up the content by combining, splitting or transforming paths;
325
- * font-icon creators can use it in both Node.js and web applications to process, optimize and test their creations.
326
-
327
-
328
- # Technical Considerations
329
-
330
- * the `optimize()` instance method will not merge path segments (for instance two or more cubic-bezier segments into one or more arc segments); however, the script will try to provide shorthand notations where possible, pick the shortest string for each segment, and generally try to deliver the best possible outcome;
331
- * all tools processing path segments will never round float values, however `pathToString`, `optimizePath` and especially `roundPath` will always round values to the default of 4 decimals; EG: 0.56676 => 0.567, 0.50 => 0.5; you can change the default option with `SVGPathCommander.options.round = 2` or remove the value rounding all together with `SVGPathCommander.options.round = false`; you can also control this feature via instance options;
332
- * the `getSVGMatrix` utility we developed will always compute the matrix by applying the transform functions in the following order: `translate`, `rotate`, `skew` and `scale`, which is the default composition/recomposition order specified in the W3C draft;
333
- * all 3d transformations as well as skews will convert `A` (arc) path commands to `C` (cubic bezier) due to the lack of resources;
334
- * while converting `A` segments to `C` segments is the shipped behavior, a validated arc-preserving alternative exists: an affine-transformed elliptical arc is still an exact elliptical arc, so `A` segments can be transformed directly via the singular value decomposition of the transformed ellipse shape matrix (radii and rotation from the eigenvalues/eigenvectors of the Gram matrix, sweep flag flipped for negative-determinant matrices). This works for any 2D matrix, and even for 3D matrices whenever the projection is orthographic (default `origin: [0,0,0]` — the `z = 0` plane is untouched by the matrix's z rows/columns, so only the 2x2 submatrix matters); the conversion to `C` is only mathematically required for perspective projections (non-zero `origin` z value or a matrix with perspective), where the arc image is a general conic. See `experiments/transformArc-tested.ts` for the implementation and rationale;
335
- * most tools included with **SVGPathCommander** should work in your Node.js apps, but feel free to report any issue;
336
- * other path commands like `R` (catmulRomBezier), `O`, `U` (ellipse and shorthand ellipse) are not present in the current draft and are not supported;
337
- * normalization can mean many things to many people and our library is developed to convert path command values to absolute and shorthand to longhand commands to provide a solid foundation for the main processing tools of our library;
338
- * when compared to the native methods like `SVGPathElement.getTotalLength()` or `SVGPathElement.getPointAtLength()`, the output of our static methods is within a [0.002 - 0.05] margin delta, but from our experience it's proven to be a more consistent outcome.
339
-
340
-
341
- # Special Thanks
342
-
343
- * Dmitry Baranovskiy for his [Raphael.js](https://dmitrybaranovskiy.github.io/raphael/)
344
- * Vitaly Puzrin & Alex Kocharin for their [SvgPath](https://github.com/fontello/svgpath)
345
- * Jürg Lehni & Jonathan Puckey for their [Paper.js](https://github.com/paperjs/paper.js/)
346
- * Andrew Willems for his [awesome guide](https://stackoverflow.com/users/5218951/andrew-willems)
347
- * Mike 'Pomax' Kamermans for his awesome [svg-path-reverse](https://github.com/Pomax/svg-path-reverse), [bezierjs](https://github.com/Pomax/bezierjs) and [bezierinfo](https://pomax.github.io/bezierinfo/)
348
- * Nicolas Debeissat for the inspiration on [svg3d](https://github.com/ndebeiss/svg3d)
349
- * Mike Bostock for his awesome [closestPoint](https://bl.ocks.org/mbostock/8027637)
350
- * James Halliday for his excelent [point-at-length](https://github.com/substack/point-at-length)
351
- * Eric Eastwood for his excelent [svg-curve-lib](https://github.com/MadLittleMods/svg-curve-lib)
352
- * PhET Interactive Simulations for their [kite](https://github.com/phetsims/kite)
353
- * [herrstrietzel](https://github.com/herrstrietzel) for his awesome [svg-pathdata-getbbox](https://github.com/herrstrietzel/svg-pathdata-getbbox)
354
- * a special thanks goes to [@vltansky](https://github.com/vltansky) for fixing tree-shaking in **SVGPathCommander**!
355
-
356
- # License
357
- **SVGPathCommander** is released under [MIT Licence](LICENSE).
59
+ | Operation | SVGPathCommander (instance) | svgpath | vs svgpath |
60
+ | ----------- | --------------------------- | ------- | ---------- |
61
+ | parse | **7.7 / 7** | 9.4 / 9 | **0.8x** |
62
+ | bbox | **5.1 / 4** | 6.8 / 6 | **0.8x** |
63
+ | transform2d | **1.5 / 0** | 3.5 / 1 | **0.4x** |
64
+ | transform3d | **8.1 / 7** | n/a | n/a |
65
+ | string | 3.6 / 3 | 3.5 / 3 | 1x |
66
+
67
+ Last benchmark run on `2026-11-15`. Generated by [`scripts/bench.js`](scripts/bench.js); update with `pnpm bench`.
68
+ <!-- BENCH:end -->
69
+
70
+ # Install
71
+
72
+ ```sh
73
+ npm install svg-path-commander
74
+ # or pnpm add svg-path-commander
75
+ # or bun add svg-path-commander
76
+ # or deno add npm:svg-path-commander
77
+ # or deno add jsr:@thednp/svg-path-commander
78
+ # or npx jsr add @thednp/svg-path-commander
79
+ ```
80
+
81
+ In a Deno project, install from [JSR](https://jsr.io/@thednp/svg-path-commander) and import the raw TypeScript source directly:
82
+
83
+ ```ts
84
+ import SVGPathCommander from "jsr:@thednp/svg-path-commander";
85
+ ```
86
+
87
+ # CDN
88
+
89
+ Version 2.2.0+
90
+
91
+ ```html
92
+ <script src="https://cdn.jsdelivr.net/npm/svg-path-commander/dist/index.min.js">
93
+ ```
94
+
95
+ Versions before 2.2.0
96
+
97
+ ```html
98
+ <script src="https://cdn.jsdelivr.net/npm/svg-path-commander/dist/svg-path-commander.js">
99
+ ```
100
+
101
+ # Quick Guide
102
+
103
+ Flip a path on the X axis:
104
+
105
+ ```js
106
+ import SVGPathCommander from "svg-path-commander";
107
+
108
+ const path = "M0 0L100 0L50 100";
109
+
110
+ const flippedPathString = new SVGPathCommander(path).flipX().toString();
111
+ // result => 'M0 100h100L50 0'
112
+ ```
113
+
114
+ Optimize a path string by using the `round` option, to round numbers to 2 decimals and finding shorthand where possible:
115
+
116
+ ```js
117
+ const optimizedPathString = new SVGPathCommander(path, { round: 2 }).optimize().toString();
118
+ ```
119
+
120
+ Or why not apply a **2D transformation** and even a **3D transformation**:
121
+
122
+ ```js
123
+ // a transform object
124
+ const transform = {
125
+ translate: 15, // X axis translation
126
+ rotate: 15, // Z axis rotation
127
+ scale: 0.75, // uniform scale on X, Y, Z axis
128
+ skew: 15, // skew 15deg on the X axis
129
+ origin: [15, 0], // if not specified, it will use the default origin value [0, 0]
130
+ };
131
+ const transformed2DPathString = new SVGPathCommander(path).transform(transform).toString();
132
+
133
+ // apply a 3D transformation
134
+ const transform = {
135
+ translate: [15, 15, 15], // `[15, 15]` would apply a 2D translation, and only `15` for X axis translation
136
+ rotate: [15, 15, 15], // or only "15" for 2D rotation on Z axis
137
+ scale: [0.7, 0.75, 0.8], // or only "0.7" for 2D scale on all X, Y, Z axis
138
+ skew: [15, 15], // or only "15" for the X axis
139
+ origin: [15, 15, 15], // full `transform-origin` for a typical 3D transformation
140
+ };
141
+ const transformed3DPathString = new SVGPathCommander(path).transform(transform).toString();
142
+ ```
143
+
144
+ Access the `bbox` instance property to apply a consistent `transform-origin`:
145
+
146
+ ```js
147
+ // apply a 3D transformation with a consistent origin
148
+ const transformed3DPath = new SVGPathCommander(path);
149
+ const { cx, cy, cz } = transformed3DPath.bbox;
150
+ const transform = {
151
+ translate: [15, 15, 15], // `[15, 15]` would apply a 2D translation, and only `15` for X axis translation
152
+ rotate: [15, 15, 15], // or only "15" for 2D rotation on Z axis
153
+ scale: [0.7, 0.75, 0.8], // or only "0.7" for 2D scale on all X, Y, Z axis
154
+ skew: [15, 15], // or only "15" for the X axis
155
+ origin: [cx, cy, cz], // the origin
156
+ };
157
+ const transformed3DPathString = transformed3DPath.transform(transform).toString();
158
+ ```
159
+
160
+ SVGPathCommander comes with a full range of additional static methods, here's how to normalize a path:
161
+
162
+ ```js
163
+ const path = "M0 0 H50";
164
+
165
+ const normalizedPath = SVGPathCommander.normalizePath(path);
166
+ // result => [['M', 0, 0], ['L', 50, 0]]
167
+ ```
168
+
169
+ Reverse a path:
170
+
171
+ ```js
172
+ const path = SVGPathCommander.parsePathString("M0 0 H50");
173
+
174
+ const reversedPath = SVGPathCommander.reversePath(path);
175
+ // result => [['M', 50, 0], ['H', 0]]
176
+ ```
177
+
178
+ Export to string:
179
+
180
+ ```js
181
+ const myPathString = SVGPathCommander.pathToString([
182
+ ["M", 0, 0],
183
+ ["L", 50, 0],
184
+ ]);
185
+ // result => 'M0 0 L50 0'
186
+ ```
187
+
188
+ Check a path string validity:
189
+
190
+ ```js
191
+ SVGPathCommander.isValidPath(path);
192
+ // result => boolean
193
+ ```
194
+
195
+ Check if path is a certain kind of `PathArray`:
196
+
197
+ ```js
198
+ SVGPathCommander.isAbsoluteArray([
199
+ ["M", 0, 0],
200
+ ["L", 50, 0],
201
+ ]);
202
+ // result => true
203
+ ```
204
+
205
+ Use treeshake and create a custom function to apply a 3D transformation using static methods:
206
+
207
+ ```ts
208
+ import { parsePathString, getPathBBox, transformPath, pathToString } from "svg-path-commander";
209
+
210
+ function myTransformFn(pathInput: string | PathArray, transformObject: TransformObject) {
211
+ const path = parsePathString(pathInput);
212
+ const { cx, cy, cz } = getPathBBox(path);
213
+
214
+ return pathToString(
215
+ transformPath(path, {
216
+ ...transformObject,
217
+ origin: [cx, cy, cz],
218
+ }),
219
+ );
220
+ }
221
+ ```
222
+
223
+ In extreme cases where performance is paramount, you can consider the parent SVG `viewBox` attribute to extract a bounding box required for a consistent transform origin.
224
+
225
+ ```ts
226
+ // const svgViewBox = document.getElementById('my-svg').getAttribute('viewBox');
227
+ const viewBox = "0 0 24 24";
228
+
229
+ const [x, y, width, height] = viewBox.split(/\s/).map(Number);
230
+ const origin = [
231
+ x + width / 2, // CX
232
+ y + height / 2, // CY
233
+ Math.max(width, height) + Math.min(width, height) / 2, // CZ
234
+ ];
235
+
236
+ // use this origin for your shape transformation
237
+ const myNewString = new SVGPathCommander("M0 0 H50")
238
+ .transform({ rotate: [35, 0, 0], origin })
239
+ .toString();
240
+ ```
241
+
242
+ Convert a shape to `<path>` and transfer all non-specific attributes
243
+
244
+ ```js
245
+ const myCircle = document.getElementById("myCircle");
246
+ SVGPathCommander.shapeToPath(myCircle, true);
247
+ ```
248
+
249
+ Alternatively you can create `<path>` from specific attributes:
250
+
251
+ ```js
252
+ const myRectAttr = {
253
+ type: "rect",
254
+ x: 25,
255
+ y: 25,
256
+ width: 50,
257
+ height: 50,
258
+ rx: 5,
259
+ };
260
+
261
+ const myRectPath = SVGPathCommander.shapeToPath(myRectAttr);
262
+ document.getElementById("mySVG").append(myRectPath);
263
+ ```
264
+
265
+ Server-side using `jsdom`:
266
+
267
+ ```js
268
+ const { document } = new JSDOM(
269
+ `<html>
270
+ <head></head>
271
+ <body>
272
+ <svg id="mySVG" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
273
+ <rect id="myRect" x="0" width="100" height="100" rx="15" />
274
+ </svg>
275
+ </body>
276
+ </html>`,
277
+ {
278
+ pretendToBeVisual: true,
279
+ },
280
+ ).window;
281
+
282
+ const myRect = document.getElementById("myRect");
283
+ SVGPathCommander.shapeToPath(myRect, true, document);
284
+ ```
285
+
286
+ Get the path length:
287
+
288
+ ```js
289
+ const myPathLength = SVGPathCommander.getTotalLength("M0 0L50 0L25 50z");
290
+ // result => 161.80339887498948
291
+ ```
292
+
293
+ Get a point along the path:
294
+
295
+ ```js
296
+ const myPoint = SVGPathCommander.getPointAtLength("M0 0L50 0L25 50z", 85);
297
+ // result => {x: 34.34752415750147, y: 31.304951684997057}
298
+ ```
299
+
300
+ Get the path bounding box:
301
+
302
+ ```js
303
+ const myPathBBox = SVGPathCommander.getPathBBox("M0 0L50 0L25 50z");
304
+ // result => {width: 50, height: 50, x: 0, y: 0, x2: 50, y2: 50, cx: 25, cy: 25, cz: 75}
305
+ ```
306
+
307
+ Find intersection points between two paths:
308
+
309
+ ```js
310
+ const count = SVGPathCommander.pathsIntersection(
311
+ "M0 50C0 0,100 0,100 50",
312
+ "M50 0C100 0,100 100,50 100",
313
+ true,
314
+ );
315
+ // result => 1
316
+
317
+ const points = SVGPathCommander.pathsIntersection(
318
+ "M0 50C0 0,100 0,100 50",
319
+ "M50 0C100 0,100 100,50 100",
320
+ false,
321
+ );
322
+ // result => [{ x: 50, y: 25, t1: 0.5, t2: 0.5 }]
323
+ ```
324
+
325
+ Equalize two paths for morphing (single subpath):
326
+
327
+ ```js
328
+ const [eq1, eq2] = SVGPathCommander.equalizeSegments(
329
+ "M0 0L100 0L50 100Z",
330
+ "M0 0L100 0L100 100L0 100Z",
331
+ );
332
+ // eq1.length === eq2.length — ready for morphing
333
+ ```
334
+
335
+ Equalize two paths for morphing (single or multi subpath):
336
+
337
+ ```js
338
+ const [eq1, eq2] = SVGPathCommander.equalizePaths(
339
+ "M0 0L100 0L50 100Z",
340
+ "M0 0L100 0L100 100L0 100Z",
341
+ { close: true },
342
+ );
343
+ // Both paths now have the same number of segments
344
+ ```
345
+
346
+ # WIKI
347
+
348
+ For developer guidelines, and a complete list of static methods, head over to the [`wiki/`](wiki/) folder in this repository.
349
+
350
+ # What Is It For?
351
+
352
+ - converting and optimizing _SVGPathElement_ for use in third party application; our [KUTE.js](https://github.com/thednp/kute.js) animation engine is using it to process _SVGPathElement_ coordinates for [SVG morphing](https://thednp.github.io/kute.js/svgMorph.html) and [SVG cubic morphing](https://thednp.github.io/kute.js/svgCubicMorph.html);
353
+ - animators that work with SVGs and need tools for performing specific path command processing;
354
+ - front-end developers looking to spice up the content by combining, splitting or transforming paths;
355
+ - font-icon creators can use it in both Node.js and web applications to process, optimize and test their creations.
356
+
357
+ # Technical Considerations
358
+
359
+ - the `optimize()` instance method will not merge path segments (for instance two or more cubic-bezier segments into one or more arc segments); however, the script will try to provide shorthand notations where possible, pick the shortest string for each segment, and generally try to deliver the best possible outcome;
360
+ - all tools processing path segments will never round float values, however `pathToString`, `optimizePath` and especially `roundPath` will always round values to the default of 4 decimals; EG: 0.56676 => 0.567, 0.50 => 0.5; you can change the default option with `SVGPathCommander.options.round = 2` or remove the value rounding all together with `SVGPathCommander.options.round = false`; you can also control this feature via instance options;
361
+ - the `getSVGMatrix` utility we developed will always compute the matrix by applying the transform functions in the following order: `translate`, `rotate`, `skew` and `scale`, which is the default composition/recomposition order specified in the W3C draft;
362
+ - all 3d transformations as well as skews will convert `A` (arc) path commands to `C` (cubic bezier) due to the lack of resources;
363
+ - while converting `A` segments to `C` segments is the shipped behavior, a validated arc-preserving alternative exists: an affine-transformed elliptical arc is still an exact elliptical arc, so `A` segments can be transformed directly via the singular value decomposition of the transformed ellipse shape matrix (radii and rotation from the eigenvalues/eigenvectors of the Gram matrix, sweep flag flipped for negative-determinant matrices). This works for any 2D matrix, and even for 3D matrices whenever the projection is orthographic (default `origin: [0,0,0]` — the `z = 0` plane is untouched by the matrix's z rows/columns, so only the 2x2 submatrix matters); the conversion to `C` is only mathematically required for perspective projections (non-zero `origin` z value or a matrix with perspective), where the arc image is a general conic. See `experiments/transformArc-tested.ts` for the implementation and rationale;
364
+ - most tools included with **SVGPathCommander** should work in your Node.js apps, but feel free to report any issue;
365
+ - other path commands like `R` (catmulRomBezier), `O`, `U` (ellipse and shorthand ellipse) are not present in the current draft and are not supported;
366
+ - normalization can mean many things to many people and our library is developed to convert path command values to absolute and shorthand to longhand commands to provide a solid foundation for the main processing tools of our library;
367
+ - when compared to the native methods like `SVGPathElement.getTotalLength()` or `SVGPathElement.getPointAtLength()`, the output of our static methods is within a [0.002 - 0.05] margin delta, but from our experience it's proven to be a more consistent outcome.
368
+
369
+ # Special Thanks
370
+
371
+ - Dmitry Baranovskiy for his [Raphael.js](https://dmitrybaranovskiy.github.io/raphael/)
372
+ - Vitaly Puzrin & Alex Kocharin for their [SvgPath](https://github.com/fontello/svgpath)
373
+ - Jürg Lehni & Jonathan Puckey for their [Paper.js](https://github.com/paperjs/paper.js/)
374
+ - Andrew Willems for his [awesome guide](https://stackoverflow.com/users/5218951/andrew-willems)
375
+ - Mike 'Pomax' Kamermans for his awesome [svg-path-reverse](https://github.com/Pomax/svg-path-reverse), [bezierjs](https://github.com/Pomax/bezierjs) and [bezierinfo](https://pomax.github.io/bezierinfo/)
376
+ - Nicolas Debeissat for the inspiration on [svg3d](https://github.com/ndebeiss/svg3d)
377
+ - Mike Bostock for his awesome [closestPoint](https://bl.ocks.org/mbostock/8027637)
378
+ - James Halliday for his excelent [point-at-length](https://github.com/substack/point-at-length)
379
+ - Eric Eastwood for his excelent [svg-curve-lib](https://github.com/MadLittleMods/svg-curve-lib)
380
+ - PhET Interactive Simulations for their [kite](https://github.com/phetsims/kite)
381
+ - [herrstrietzel](https://github.com/herrstrietzel) for his awesome [svg-pathdata-getbbox](https://github.com/herrstrietzel/svg-pathdata-getbbox)
382
+ - a special thanks goes to [@vltansky](https://github.com/vltansky) for fixing tree-shaking in **SVGPathCommander**!
383
+
384
+ # License
385
+
386
+ **SVGPathCommander** is released under [MIT Licence](LICENSE).