-
Notifications
You must be signed in to change notification settings - Fork 85
Low level API
At the heart of the library there is a very simple API to compose SVG paths by method chaining. At this level, we do not try to abstract away the specification of SVG paths, and the parameters mimic exactly the ones in the specification. An empty path object is created with the function Path()
and complex path objects can be obtained from the empty one by chaining path methods. Thus, one can produce a path like:
var Path = require('paths/path');
var path = Path()
.moveto(10, 20)
.lineto(30, 50)
.lineto(25, 28)
.qcurveto(27, 30, 32, 27)
.closepath();
Other than methods to compose other paths, path objects have the methods print
and points
. The print
method will give the textual representation of the path, that can be used inside an SVG figure like:
<!-- inside a template -->
<svg width=300 height=300>
<path d="{{ path.print() }}" fill="blue" />
</svg>
The points
method returns the array of points through which the path passes. This case be useful, for instance, to place labels near the endpoints.
The instructions
method returns the array of instructions to build the path. This is used to access programmatically the single instructions and to join paths.
The connect
method, applied to another path, adds the second path to the first one: if the end point of the first path is different from the start point of the second path, they are joined by a straight line.
All methods except print
and points
produce a new path (paths are immutable). These methods mimic the SVG path specification and are moveto
, lineto
, hlineto
, vlineto
, curveto
, qcurveto
, smoothcurveto
, smoothqcurveto
and closepath
.
It is also possible to use a more verbose API, where the parameters to the path methods are named. To do so, just pass an object to the path methods. The names of the parameters are the same as in the SVG specification. Hence:
Path()
.moveto(2, 10)
.lineto(3, 5)
.hlineto(4)
.vlineto(3)
.curveto(1, 1, 2, 5, 3, 1)
.smoothcurveto(2, 5, 2, 6)
.qcurveto(0, 1, 2, 3)
.smoothqcurveto(6, -3)
.arc(3, 3, 2, 0, 1, 6, -3)
.closepath()
is equivalent to:
Path()
.moveto({x: 2, y: 10})
.lineto({x: 3, y: 5})
.hlineto({x: 4})
.vlineto({y: 3})
.curveto({x1: 1, y1: 1, x2: 2, y2: 5, x: 3, y:1})
.smoothcurveto({x2: 2, y2: 5, x: 2, y: 6})
.qcurveto({x1: 0, y1: 1, x: 2, y: 3})
.smoothqcurveto({x: 6, y: -3})
.arc({rx: 3, ry: 3, xrot: 2, largeArcFlag: 0, sweepFlag: 1, x: 6, y: -3})
.closepath()
The verbose API can be freely mixed with the shorter one, so for instance:
Path()
.moveto(2, 10)
.lineto(3, 5)
.curveto({x1: 1, y1: 1, x2: 2, y2: 5, x: 3, y:1})
.smoothcurveto(2, 5, 2, 6)
.qcurveto({x1: 0, y1: 1, x: 2, y: 3})
is perfectly valid.
NOTE: largeArcFlag
used to be large_arc_flag
before 0.4. Similarly, sweepFlag
used to be sweep_flag
.