vector-path-tools
Geometry for vector paths made of lines and quadratic and cubic Bézier curves: exact bounding boxes, hit testing, boolean operations, lengths and points along paths, splitting and offsetting curves, flattening curves into lines within a tolerance, converting cubics to quadratics, and SVG arcs as cubics. Pure TypeScript, no dependencies.
npm install vector-path-tools
import { arcTo, bounds, contains, flatten, toQuadratics } from 'vector-path-tools';
const path = [
{ type: 'moveTo', x: 0, y: 0 },
{ type: 'cubicTo', c1x: 0, c1y: 100, c2x: 100, c2y: 100, x: 100, y: 0 },
{ type: 'close' },
];
bounds(path); // { minX: 0, minY: 0, maxX: 100, maxY: 75 }: the curve, not its control points
contains(path, 50, 70); // true: inside the fill
flatten(path); // only moveTo / lineTo / close, every line within 0.25 of the curve
toQuadratics(path, 0.1); // the cubic as quadratics within 0.1
// an SVG arc as cubics, to put in a path
const halfCircle = [{ type: 'moveTo', x: 0, y: 0 }, ...arcTo(0, 0, 50, 50, 0, false, true, 100, 0)];
Every example below is live: drag the round points (filled: on the curve; hollow: control points).
Paths
A path is an array of commands in absolute coordinates:
[
{ type: 'moveTo', x: 0, y: 0 },
{ type: 'lineTo', x: 100, y: 0 },
{ type: 'quadTo', cx: 150, cy: 50, x: 100, y: 100 },
{ type: 'cubicTo', c1x: 50, c1y: 150, c2x: 0, c2y: 50, x: 0, y: 100 },
{ type: 'close' },
]
There is no arc command: arcTo turns an SVG
arc into cubic commands to put in the path. Every function returns a new array
and leaves its input alone. Invalid input (a drawing command before any
moveTo, an unknown command, a NaN or infinite coordinate) is a
TypeError.
curvePoint(curve, t) and curveTangent(curve, t)
One curve's point at its parameter t, and its derivative there: the
direction it runs, with its speed as the length. Equal steps in
t aren't equal distances along the curve; for those, use
measureCurve (below) or measure.
curvePoint([p0, p1, p2, p3], 0.5); // { x, y }
curveTangent(segments(path)[0], 0); // { x, y }: Math.atan2(y, x) is the angle
splitCurve(curve, t) and measureCurve(curve)
One curve split at its parameter t, or at each of an array of them,
as segments of the same kind that together draw exactly the curve (de
Casteljau's construction). measureCurve measures one curve once,
for its length and its parameter at a distance along it, to split it at
distances instead.
const [before, after] = splitCurve(curve, 0.5);
const m = measureCurve(curve);
splitCurve(curve, [10, 20, 30].map(m.tAtLength)); // at 10, 20 and 30 along
offsetCurve(curve, distance, options?)
One curve moved sideways by distance at every point, as segments of
the same kind, within options.tolerance of the exact offset (in
path units, default 0.25). Positive distances are on the right on screen. Where
the distance exceeds the curve's radius of curvature, the offset folds into a
cusp, and a segment ends there. One curve at a time: a whole path also needs
joins, which is stroking.
offsetCurve([p0, p1, p2, p3], 4); // [{ type: 'cubic', p0, p1, p2, p3 }, ...]
offsetCurve(segments(path)[0], -4, { tolerance: 0.01 });
measure(path, options?) and pointsAlong(path, spacing)
A path's length, and points with their direction at a distance or a fraction of
it, accurate to 1e-10 of each curve's length at any scale. Subpaths continue one
into the next, as in SVG. pointsAlong spaces points evenly along
each subpath, as p5's textToPoints does for glyphs.
const m = measure(path);
m.length; // the total length (a close line counts)
m.subpathLengths; // each subpath's length
m.pointAtLength(120); // { x, y, angle }: 120 along the path, angle in radians
m.pointAtFraction(0.5); // halfway
pointsAlong(path, 20); // [[{ x, y, angle }, ...], ...]: one array per subpath
splitPath(path, distances, options?)
The path cut at distances along it, as pieces that are paths of their own.
Distances run on across subpaths as in measure, but pieces never
cross a moveTo. On a closed subpath the last piece runs across the
start to the first cut, so n cuts give n pieces; on an open one, n + 1. Cuts
that would leave a piece of no length, at an open subpath's ends or within the
measuring tolerance of each other, are dropped.
const m = measure(path);
splitPath(path, [m.length / 3, (2 * m.length) / 3]); // [[{ type: 'moveTo', ... }, ...], ...]
bounds(path)
The exact bounding box of what the path draws: curves count by their extremes,
not their control points. null for a path that draws nothing.
bounds(path); // { minX, minY, maxX, maxY }, or null
contains(path, x, y, options?), area(path) and
subpaths(path)
Whether a point is inside the path's fill: Skia's
SkPath::contains (default) or fontTools'
PointInsidePen. The fill rule decides how nested subpaths combine:
under 'nonzero', a hole must wind the other way; under
'evenodd', every nested loop is a hole. area is the
exact signed area, positive where a subpath runs clockwise on screen (y down);
taken per subpath, its sign shows which way each one winds.
contains(path, 50, 70); // true or false
contains(path, 50, 70, { fillRule: 'evenodd', method: 'fonttools' });
area(path); // every subpath's signed area added up
subpaths(path).map(area); // each subpath's: > 0 clockwise on screen
booleanOp(a, b, operation, options?)
Union, intersection, difference or exclusion of two paths' fills, as simple, closed contours: outer ones clockwise on screen, holes the other way, so the result fills the same under either fill rule. Curves are only split where edges meet, never approximated. Each path has its own fill rule, so a path's own overlaps are resolved too.
booleanOp(a, b, 'difference'); // inside a and not inside b
booleanOp(a, b, 'union', { fillRuleA: 'evenodd' });
booleanOp(glyph, [], 'union'); // a glyph without overlapping contours
toQuadratics(path, tolerance?, options?)
Cubics replaced by quadratics within tolerance: kurbo's
to_quads (default), fontTools' cu2qu (a smooth spline), or one of
Adrian Colomitchi's three methods (from his bezier-utils, with three bugs
fixed), optionally split at inflection points first. tolerance
defaults to 1 for fontTools (0.001 em at 1000 units per em) and 0.5 for
Colomitchi's methods (0.5 px at the least), and is required for kurbo, which
suggests no value.
toQuadratics(path, 0.1); // kurbo: the tolerance is required
toQuadratics(path, undefined, { method: 'fonttools' }); // tolerance 1
toQuadratics(path, 0.5, { method: 'colomitchi-adaptive', detectInflections: true });
flatten(path, tolerance?, options?)
Curves replaced by lines within tolerance of the curve (in path
units: on screen, about 0.25 px divided by the zoom; default 0.25). Two methods
choose where the lines go; the
flatten comparison shows them side by
side.
flatten(path); // only moveTo / lineTo / close, every line within 0.25 of the curve
flatten(path, 0.1, { method: 'adaptive' });
| Method | How | Within the tolerance | Lines on cubics | Time |
|---|---|---|---|---|
'uniform' (default) |
Equal steps per curve, as many as Wang's formula needs (Skia) | Proven | 100% | 1× |
'adaptive' |
Lines spaced by how much the curve bends: kurbo's flatten (Raph Levien's method) | Not guaranteed (up to 2.6× on cubics) | 52–54% | 1.3–1.9× |
Measured on random cubics. kurbo spreads one line count over a cubic's
quadratics, so on cubics 'adaptive' can go past the tolerance; on
quadratics it stays within about 6%.
arcTo(x0, y0, rx, ry, xAxisRotation, largeArc, sweep, x, y)
An SVG elliptical arc (the A command) from (x0, y0) to (x, y) as
path commands: cubics, ported from svg-arc-to-cubic-bezier. As the SVG spec
says, identical end points give no commands and a zero radius gives a
lineTo.
const path = [
{ type: 'moveTo', x: 0, y: 0 },
...arcTo(0, 0, 50, 50, 0, false, true, 100, 0), // a half circle
];
References
What each part is ported from or based on, at the versions the ports follow. Licenses: see THIRD_PARTY_NOTICES.
-
Skia (BSD-3-Clause), commit
50ba8e6: Wang's formula (WangsFormula.h,Tessellation.h), the curve evaluation of its tessellation shader (GrPathTessellationShader.cpp,PatchWriter.h), andSkPath::contains(SkPathPriv.cpp,SkPathPriv.h,SkGeometry.cpp,SkCubicClipper.cpp,SkScalar.h). -
kurbo (MIT), commit
a5f97ff:flattenandCubicBez::to_quads(bezpath.rs,quadbez.rs,cubicbez.rs). -
fontTools, commit
1ff10da: cu2qu (Apache-2.0;cu2qu.py,errors.py) andPointInsidePen(MIT;pointInsidePen.py,basePen.py,bezierTools.py). -
Adrian Colomitchi (caffeineowl.com): bezier-utils (MIT,
bezier-utils-src.jar) and the articles "Approximating cubic Bezier curves by quadratic ones" (2006) and "Inflection points of a cubic Bezier" (2004) (archived copies). -
svg-arc-to-cubic-bezier
(ISC), commit
f02ab11:index.js, forarcTo. -
bezierjs (MIT), commit
4e76729:utils.js, whose 24-point Legendre–Gauss arc length stroke-outline's is based on, formeasureandpointsAlong(with error control and points at a distance added in this library); andbezier.js, whosesimple,scaleandreducestroke-outline's curve offsetting is based on, foroffsetCurve.
More
-
flattencomparison: the two methods on the same curve, with measured errors. -
toQuadraticscomparison: the five methods on the same cubic, with measured errors. - README for the full API.