SVG has the path element, which allows to draw complex lines and curves. JavaScript has some methods to get properties from paths, such as getTotalLength() and getPointAtLength(), which are very useful when e.g. creating SVG animations with D3js transitions.

Unfortunately, when working with a Canvas element, or when working with nodejs, these functions are not available, making very difficult to obtain these informations.

That’s why I made the svg-path-properties library

svg-path-properties library

Install

To use with npm, just type:

npm install svg-path-properties

To use it directly from the browser, include the script and call it with the prefix spp:

<script src="https://unpkg.com/svg-path-properties@0.1.1/build/path-properties.min.js"></script>
spp.svgPathProperties(path(track));

Usage

First, require the library and initialize it with the path string:

var path = require("svg-path-properties");
var properties = path.svgPathProperties("M0,100 Q50,-50 100,100 T200,100");

Then, access the different properties with the different methods

Get the path total length in pixels:

var length = properties.getTotalLength();

Get the point on the path at certain length (in pixels):

var point = properties.getPointAtLength(200);

Get the tangent vector at certain length (in pixels):

var tangent = properties.getTangentAtLength(200);

Get the point position and the tangent vector at the same time (more efficient than doing it with the separate methods):

var allProperties = properties.getPropertiesAtLength(200);

Some examples

Canvas & svg-path-properties Point-Along-Path Interpolation: Canvas version of this block by Mike Bostock.

Canvas path animation: A path on a map that draws itself to show a train route.

Label positioning with svg-path-properties: Isolines labeling. Finding the position and angle isn’t possible even with SVG paths alone.

Drawing streamlines from a GeoTIFF file: Marking the streamlines direction with an arrow isn’t possible if the position and tangent is unknown.

I would be very happy to know if somebody is using it and creates something with the library.