svg-path-utils
Some utilities for svg path element to help operating with path data, like calculating inverse path data...
Install
npm install svg-path-utils
Usage
var spu = ;var utils = ;
or in es6
;const utils = ;
then
// generate path dataconst d = utils; // d = "M50,100 L200,300 Z" // calculate inverse path dataconst inverse_d = utils; // inverse_d = "M200,300 L50,100 Z"
Example
Inverse path data calculation
Direct Path | Inverse Path |
---|---|
d="M50,300 L50,250 C50,150 75,150 100,250 C150,450 200,450 200,250 Q200,100 400,100" |
d="M400,100 Q200,100 200,250 C200,450 150,450 100,250 C75,150 50,150 50,250 L50,300" |
Check this online demo.
It is also used in Yarrow.
API Reference
Path data commands (operators)
Uppercase (M, L, H, ...) - uses absolute coordinates, lowercase (m, l, h, ...) - uses relative coordinates
# utils.M(x, y) - “moveto” commands.
# utils.m(x, y)
# utils.L(x, y) - “lineto” commands.
# utils.l(x, y)
# utils.H(x) - horizontal “lineto” commands.
# utils.h(x)
# utils.V(y) - vertical “lineto” commands.
# utils.v(y)
# utils.C(x1, y1, x2, y2, x, y) - cubic Bézier curve commands.
# utils.c(x1, y1, x2, y2, x, y)
# utils.S(x2, y2, x, y) - smooth cubic Bézier curve commands.
# utils.s(x2, y2, x, y)
# utils.Q(x1, y1, x, y) - quadratic Bézier curve commands.
# utils.q(x1, y1, x, y)
# utils.T(x, y) - smooth quadratic Bézier curve commands.
# utils.t(x, y)
# utils.Z() - “closepath” commands.
# utils.z()
Todo: add .A(...) and .a(...) - elliptical arc curve commands.
Example of usage:
utils // return: "M50,100"utils // return: "L200,300"utils // return: "c10,20 30,40 50,60"utils // return: "Z"
Path data utils
# utils.parse(d)
Parse path data d into sequence of operators ['M', 'L', ...] and sequence of principal points [(x,y)].
utils; /* return: { operators: ["M", "L", "H"], points: [ {x: 50, y: 100}, {x: 200, y: 300}, {x: 100} ] }*/
# utils.generate({ operators: [operators], points: [points]})
Generate path data d from a sequence of operators ['M', 'L', ...] and sequence of principal points [(x,y)].
const data = operators: "M" "L" "H" points: x: 50 y: 100 x: 200 y: 300 x: 100 utils; // return: "M50,100 L200,300 H100"
# utils.inversePath(d)
Calculate and return inverse path data for path data d.
utils; // return: "M200,300 L50,100 Z"
# utils.join(args)
Join input args into a string with space (' ') separator.
utils; // return: "M50,100 L200,300 Z"utils; // return: "M50,100 L200,300 Z"
Licence
MIT