svg-path-commander 2.3.5 → 2.4.0

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
@@ -9,15 +9,25 @@
9
9
 
10
10
  ![image](./docs/assets/SVGPathCommander.svg)
11
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>`.
12
+ A modern set of TypeScript tools for manipulating the `d` (description) attribute for _SVGPathElement_ items. The library provides a modern JavaScript-style API for reusable path strings with high-fidelity geometry; coordinates are rounded to four decimals by default, or left exact with `round: "off"`. In addition, you have a powerful tool to convert other SVG shapes like `<circle>` or `<rect>` to `<path>`.
13
13
 
14
14
  While you may find familiar tools inside, this library brings _**new additions**_:
15
15
 
16
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
17
  - thanks to the community contributions we've implemented useful tools like `getPropertiesAtLength`, `getSegmentOfPoint` or `isPointInStroke`;
18
+ - `getPropertiesAtLength` returns the frame of the path at a given length — the point, the unit tangent vector, the unit normal vector and the angle of the tangent in degrees;
19
+ - `simplifyPath` reduces straight-line runs with Douglas-Peucker and fits curve runs with fewer cubic Béziers, preserving arcs and original curves when fitting would not reduce the segment count;
20
+ - `resamplePath` distributes the points of every sub-path along its own length, keeps the source segment boundaries and corners when the requested count allows it, and never connects two sub-paths;
21
+ - `offsetPath` offsets a path along its normals, with the joins and the caps of a stroke, so a path can be expanded or outlined;
22
+ - `isPointInPath` tells if a point is inside a filled shape, with the `nonzero` and the `evenodd` fill rules of the SVG `fill-rule` attribute;
23
+ - `isPointInStroke` tells if a point is along a path, or inside the band a stroke paints around it when you give it a width;
24
+ - `equalize` brings two paths to the same shape, so they can be morphed into each other;
18
25
  - a tool that can _reverse path draw direction_ without altering path commands, even with specific shorthand path commands;
19
26
  - 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.
27
+ - a new and unique tool to _apply transform functions to path commands_ via the modern _DOMMatrix_ API;
28
+ - the geometry queries read a shared length table, so `getPropertiesAtLength`, `getPointAtLength` and the closest point search are linear in the number of segments instead of quadratic — a 4 000 segment path answers a length query in about half a millisecond and a closest point query in under two milliseconds;
29
+ - the library has two entry points: the main entry holds the class and its static methods, while the tree-shakeable utility entry holds every standalone tool, including the morphing and intersection engines;
30
+ - every tool has a defined answer for an empty or malformed path, and the copy-based path tools leave the source path unchanged.
21
31
 
22
32
  **The key differences with other libraries**:
23
33
 
@@ -40,31 +50,32 @@ This library is available on [CDN](https://www.jsdelivr.com/package/npm/svg-path
40
50
 
41
51
  # Performance
42
52
 
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.
53
+ 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 `vpr bench` against a sample path with `11650` path segments. All values are in **milliseconds**, reported as the **median** and the **best** of 30 runs after 5 warmups; lower is better. The `vs svgpath` column is the median ratio of SVGPathCommander to svgpath.
44
54
 
45
55
  `transform2d` uses `{ scale: 0.8 }`, `transform3d` uses `{ rotate: [15, 15, 30] }`. [SvgPath](https://github.com/fontello/svgpath) only supports 2D transforms, so `transform3d` is marked `n/a` for it.
46
56
 
47
57
  ## Static methods
48
58
 
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 |
59
+ | Operation | SVGPathCommander median | SVGPathCommander best | svgpath median | svgpath best | vs svgpath |
60
+ | ----------- | ----------------------- | --------------------- | -------------- | ------------ | ---------- |
61
+ | parse | **5** | 4.7 | 8.9 | 8.9 | **0.6x** |
62
+ | bbox | **4.4** | 4.3 | 6.2 | 6 | **0.7x** |
63
+ | transform2d | **1.2** | 1.1 | 1.3 | 1.2 | **0.9x** |
64
+ | transform3d | **12.4** | 11.2 | n/a | n/a | n/a |
65
+ | string | **3** | 2.9 | 3.8 | 3.1 | **0.8x** |
56
66
 
57
67
  ## Instance methods
58
68
 
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 |
69
+ | Operation | SVGPathCommander median | SVGPathCommander best | svgpath median | svgpath best | vs svgpath |
70
+ | ----------- | ----------------------- | --------------------- | -------------- | ------------ | ---------- |
71
+ | parse | **4.7** | 4.7 | 8.9 | 8.9 | **0.5x** |
72
+ | bbox | **4.3** | 4.3 | 6.2 | 6 | **0.7x** |
73
+ | transform2d | **0.7** | 0.6 | 1.3 | 1.2 | **0.6x** |
74
+ | transform3d | **7.5** | 6.8 | n/a | n/a | n/a |
75
+ | string | **1.2** | 1.2 | 3.8 | 3.1 | **0.3x** |
76
+
77
+ Last benchmark run on `2026-11-23`. Generated by [`scripts/bench.js`](scripts/bench.js); update with `vpr bench --write`.
66
78
 
67
- Last benchmark run on `2026-11-15`. Generated by [`scripts/bench.js`](scripts/bench.js); update with `pnpm bench`.
68
79
  <!-- BENCH:end -->
69
80
 
70
81
  # Install
@@ -84,6 +95,31 @@ In a Deno project, install from [JSR](https://jsr.io/@thednp/svg-path-commander)
84
95
  import SVGPathCommander from "jsr:@thednp/svg-path-commander";
85
96
  ```
86
97
 
98
+ # Entry Points
99
+
100
+ The library ships two entry points, so a bundle only carries the tools it uses:
101
+
102
+ | Entry point | Holds |
103
+ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
104
+ | `svg-path-commander` | the `SVGPathCommander` class, its static methods and the public types |
105
+ | `svg-path-commander/util` | every standalone tool — parsing, conversion, geometry, processing, morphing and intersection — in one tree-shakeable entry |
106
+
107
+ ```ts
108
+ import SVGPathCommander from "svg-path-commander";
109
+ import { equalize, getPathBBox, pathToCurve, pathsIntersection } from "svg-path-commander/util";
110
+ ```
111
+
112
+ The JSR package has the same utility entry: `jsr:@thednp/svg-path-commander/util`.
113
+
114
+ The main entry holds every engine as a static field, so the class and its static methods always
115
+ include the morphing and intersection tools. The utility entry contains the same tools as standalone
116
+ functions, and a bundler drops the exports an application does not use:
117
+
118
+ | You need | Import |
119
+ | ------------------------------------- | ------------------------- |
120
+ | the class, with its chainable methods | `svg-path-commander` |
121
+ | standalone tools, without the class | `svg-path-commander/util` |
122
+
87
123
  # CDN
88
124
 
89
125
  Version 2.2.0+
@@ -108,7 +144,7 @@ import SVGPathCommander from "svg-path-commander";
108
144
  const path = "M0 0L100 0L50 100";
109
145
 
110
146
  const flippedPathString = new SVGPathCommander(path).flipX().toString();
111
- // result => 'M0 100h100L50 0'
147
+ // result => 'M100 0H0L50 100'
112
148
  ```
113
149
 
114
150
  Optimize a path string by using the `round` option, to round numbers to 2 decimals and finding shorthand where possible:
@@ -182,7 +218,7 @@ const myPathString = SVGPathCommander.pathToString([
182
218
  ["M", 0, 0],
183
219
  ["L", 50, 0],
184
220
  ]);
185
- // result => 'M0 0 L50 0'
221
+ // result => 'M0 0L50 0'
186
222
  ```
187
223
 
188
224
  Check a path string validity:
@@ -205,7 +241,8 @@ SVGPathCommander.isAbsoluteArray([
205
241
  Use treeshake and create a custom function to apply a 3D transformation using static methods:
206
242
 
207
243
  ```ts
208
- import { parsePathString, getPathBBox, transformPath, pathToString } from "svg-path-commander";
244
+ import { parsePathString, getPathBBox, transformPath, pathToString } from "svg-path-commander/util";
245
+ import type { PathArray, TransformObject } from "svg-path-commander";
209
246
 
210
247
  function myTransformFn(pathInput: string | PathArray, transformObject: TransformObject) {
211
248
  const path = parsePathString(pathInput);
@@ -297,6 +334,18 @@ const myPoint = SVGPathCommander.getPointAtLength("M0 0L50 0L25 50z", 85);
297
334
  // result => {x: 34.34752415750147, y: 31.304951684997057}
298
335
  ```
299
336
 
337
+ Get the frame of the path at a given length — the point, the unit tangent vector, the unit
338
+ normal vector and the angle of the tangent in degrees:
339
+
340
+ ```js
341
+ const myFrame = SVGPathCommander.getPropertiesAtLength("M0 0L50 0L25 50z", 85);
342
+ // result => { segment: ["L", 25, 50], index: 2, length: 55.90169943749474, lengthAtSegment: 50,
343
+ // point: {x: 34.34752415750147, y: 31.304951684997057},
344
+ // tangent: {x: -0.4472135954999579, y: 0.8944271909999159},
345
+ // normal: {x: -0.8944271909999159, y: -0.4472135954999579},
346
+ // angle: 116.56505117707799 }
347
+ ```
348
+
300
349
  Get the path bounding box:
301
350
 
302
351
  ```js
@@ -304,6 +353,56 @@ const myPathBBox = SVGPathCommander.getPathBBox("M0 0L50 0L25 50z");
304
353
  // result => {width: 50, height: 50, x: 0, y: 0, x2: 50, y2: 50, cx: 25, cy: 25, cz: 75}
305
354
  ```
306
355
 
356
+ Simplify the path, within a tolerance:
357
+
358
+ ```js
359
+ const mySimplifiedPath = SVGPathCommander.simplifyPath("M0 0L10 0L20 0L30 0", 1);
360
+ // result => [["M", 0, 0], ["L", 30, 0]]
361
+ ```
362
+
363
+ Resample every sub-path to a given number of points, distributed along its own length:
364
+
365
+ ```js
366
+ const myResampledPath = SVGPathCommander.resamplePath("M0 0L100 0L100 100", 3);
367
+ // result => [["M", 0, 0], ["L", 100, 0], ["L", 100, 100]]
368
+
369
+ const myResampledIcon = SVGPathCommander.resamplePath("M0 0L10 0M20 0L30 0", 2);
370
+ // result => [["M", 0, 0], ["L", 10, 0], ["M", 20, 0], ["L", 30, 0]]
371
+ ```
372
+
373
+ The `count` is the number of points of every sub-path. The sub-paths stay separate, so resampling
374
+ an icon never connects one part of it to another.
375
+
376
+ Offset the path along its normals — the `side` is literal, the left side is the left
377
+ normal of the direction of travel, and the `both` side is the outline of the stroke:
378
+
379
+ ```js
380
+ const myOffsetPath = SVGPathCommander.offsetPath("M0 0L100 0", 10);
381
+ // result => [["M", 0, 10], ["L", 100, 10]]
382
+
383
+ const myOutline = SVGPathCommander.offsetPath("M0 0L100 0", 10, { side: "both" });
384
+ // result => [["M", 0, 10], ["L", 100, 10], ["L", 100, -10], ["L", 0, -10], ["Z"]]
385
+ ```
386
+
387
+ Join two paths into a single path with two sub-paths, and reverse one sub-path of a path:
388
+
389
+ ```js
390
+ const myJoinedPath = SVGPathCommander.joinPath("M0 0L100 0", "M0 100L100 100");
391
+ // result => [["M", 0, 0], ["L", 100, 0], ["M", 0, 100], ["L", 100, 100]]
392
+
393
+ const myReversedSubPath = SVGPathCommander.reverseSubPath("M0 0L100 0ZM0 100L100 100", 1);
394
+ // result => [["M", 0, 0], ["L", 100, 0], ["Z"], ["M", 100, 100], ["L", 0, 100]]
395
+ ```
396
+
397
+ Tell if a point is inside a filled shape — the `nonzero` and the `evenodd` fill rules of the
398
+ SVG `fill-rule` attribute are both supported, and a point on the boundary of the shape is
399
+ inside of it:
400
+
401
+ ```js
402
+ const myHitTest = SVGPathCommander.isPointInPath("M0 0L100 0L100 100L0 100Z", { x: 50, y: 50 });
403
+ // result => true
404
+ ```
405
+
307
406
  Find intersection points between two paths:
308
407
 
309
408
  ```js
@@ -319,7 +418,7 @@ const points = SVGPathCommander.pathsIntersection(
319
418
  "M50 0C100 0,100 100,50 100",
320
419
  false,
321
420
  );
322
- // result => [{ x: 50, y: 25, t1: 0.5, t2: 0.5 }]
421
+ // result => [{ x: 80.41363825007447, y: 19.586361749925548, t1: 0.7262151274035185, t2: 0.27378487259648177 }]
323
422
  ```
324
423
 
325
424
  Equalize two paths for morphing (single subpath):
@@ -343,9 +442,41 @@ const [eq1, eq2] = SVGPathCommander.equalizePaths(
343
442
  // Both paths now have the same number of segments
344
443
  ```
345
444
 
445
+ Multi-subpath paths keep their outer contours and holes. Outer contours only match outer contours
446
+ and holes only match holes. The paths are reversed as whole paths, so their outer/hole relationships
447
+ stay intact, and every unmatched contour receives a placeholder at its own centroid instead of being
448
+ dropped. Closed contours keep their `Z` commands by default, open paths stay open, and a mixed pair
449
+ is closed on both sides to keep the commands compatible; pass `close: false` to leave both results
450
+ open.
451
+
452
+ Equalize two paths for morphing — the recommended entry point, it picks the right
453
+ strategy for the paths, aligns their points and normalizes their winding:
454
+
455
+ ```js
456
+ const [eq1, eq2] = SVGPathCommander.equalize("M0 0L100 0L50 100Z", "M0 0L100 0L100 100L0 100Z", {
457
+ strategy: "arcLength",
458
+ });
459
+ // eq1.length === eq2.length — ready for morphing
460
+ ```
461
+
462
+ The `strategy` option decides how the points of the paths are placed: `segment`
463
+ (the default) splits the segments of the paths, so the points of the result are
464
+ the points of the paths, while `arcLength` distributes the result points along
465
+ the path length and keeps the source segment boundaries and corners when the
466
+ requested count allows it:
467
+
468
+ ```js
469
+ const [eq1, eq2] = SVGPathCommander.equalize("M0 0C50 100 100 100 150 0", "M0 0L150 0L150 100Z", {
470
+ strategy: "arcLength",
471
+ points: 8,
472
+ mode: "curve",
473
+ });
474
+ // eq1.length === eq2.length === 9 — ready for morphing
475
+ ```
476
+
346
477
  # WIKI
347
478
 
348
- For developer guidelines, and a complete list of static methods, head over to the [`wiki/`](wiki/) folder in this repository.
479
+ For developer guidelines and the API reference, head over to the [`wiki/`](wiki/) folder in this repository.
349
480
 
350
481
  # What Is It For?
351
482
 
@@ -357,11 +488,12 @@ For developer guidelines, and a complete list of static methods, head over to th
357
488
  # Technical Considerations
358
489
 
359
490
  - 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;
491
+ - most geometry and transformation tools preserve float values. `pathToString()` and `roundPath()` use 4 decimals by default, while static `optimizePath()` uses 2 decimals by default; e.g. `0.56676` becomes `0.5668` at 4 decimals and `0.57` at 2. Pass `"off"` to `pathToString()` or `roundPath()`, or set `SVGPathCommander.options.round = "off"`, to disable their rounding. An instance created with `{ round: "off" }` keeps exact coordinates in `toString()`, but `optimize()` still uses its 2-decimal optimizer;
361
492
  - 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
493
  - all 3d transformations as well as skews will convert `A` (arc) path commands to `C` (cubic bezier) due to the lack of resources;
363
494
  - 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
495
  - most tools included with **SVGPathCommander** should work in your Node.js apps, but feel free to report any issue;
496
+ - the copy-based path tools leave the source path unchanged; `iterate()` is the explicit exception and updates the path array it receives, while the chainable instance methods intentionally replace the path of their instance;
365
497
  - other path commands like `R` (catmulRomBezier), `O`, `U` (ellipse and shorthand ellipse) are not present in the current draft and are not supported;
366
498
  - 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
499
  - 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.