• Stars
    star
    205
  • Rank 191,264 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A parser for SVG's path syntax

svg-path-parser stable

An SVG path parser, originally built from the PEG.js grammar specified here, published as an NPM module.

Grammar originally written by Gavin Kistner.

svg-path-parser

Usage

require('svg-path-parser')(d)

Takes an SVG path string. The following code…

var parseSVG = require('svg-path-parser');
var d='M3,7 5-6 L1,7 1e2-.4 m-10,10 l10,0  \
  V27 89 H23           v10 h10             \
  C33,43 38,47 43,47   c0,5 5,10 10,10     \
  S63,67 63,67         s-10,10 10,10       \
  Q50,50 73,57         q20,-5 0,-10        \
  T70,40               t0,-15              \
  A5,5 45 1,0 40,20    a5,5 20 0,1 -10-10  Z';
console.log(parseSVG(d));

…will yield an array of commands that define the path, like so:

[ { code:'M', command:'moveto', x:3, y:7 },
  { code:'L', command:'lineto', x:5, y:-6 },
  { code:'L', command:'lineto', x:1, y:7 },
  { code:'L', command:'lineto', x:100, y:-0.4 },
  { code:'m', command:'moveto', relative:true, x:-10, y:10 },
  { code:'l', command:'lineto', relative:true, x:10, y:0 },
  { code:'V', command:'vertical lineto', y:27 },
  { code:'V', command:'vertical lineto', y:89 },
  { code:'H', command:'horizontal lineto', x:23 },
  { code:'v', command:'vertical lineto', relative:true, y:10 },
  { code:'h', command:'horizontal lineto', relative:true, x:10 },
  { code:'C', command:'curveto', x1:33, y1:43, x2:38, y2:47, x:43, y:47 },
  { code:'c', command:'curveto', relative:true, x1:0, y1:5, x2:5, y2:10, x:10, y:10 },
  { code:'S', command:'smooth curveto', x2:63, y2:67, x:63, y:67 },
  { code:'s', command:'smooth curveto', relative:true, x2:-10, y2:10, x:10, y:10 },
  { code:'Q', command:'quadratic curveto', x1:50, y1:50, x:73, y:57 },
  { code:'q', command:'quadratic curveto', relative:true, x1:20, y1:-5, x:0, y:-10 },
  { code:'T', command:'smooth quadratic curveto', x:70, y:40 },
  { code:'t', command:'smooth quadratic curveto', relative:true, x:0, y:-15 },
  { code:'A', command:'elliptical arc', rx:5, ry:5, xAxisRotation:45, largeArc:true, sweep:false, x:40, y:20 },
  { code:'a', command:'elliptical arc', relative:true, rx:5, ry:5, xAxisRotation:20, largeArc:false, sweep:true, x:-10, y:-10 },
  { code:'Z', command:'closepath' } ]

Alternatively, from version 1.1 on, the module exports multiple functions that you can separately use:

const {parseSVG, makeAbsolute} = require('svg-path-parser');

Absolute Path Commands

Version 1.1 adds the ability to convert an array of path commands into their absolute-coordinate equivalents. This modifies the parsed command objects in place, and also returns the array of commands. Continuing the example above:

const {parseSVG, makeAbsolute} = require('svg-path-parser');
const commands = parseSVG(d);
makeAbsolute(commands); // Note: mutates the commands in place!
console.log(commands);
[ { code:'M', command:'moveto',                   x0:0, y0:0 x:3, y:7 },
  { code:'L', command:'lineto',                   x0:3, y0:7 x:5, y:-6 },
  { code:'L', command:'lineto',                   x0:5, y0:-6 x:1, y:7 },
  { code:'L', command:'lineto',                   x0:1, y0:7 x:100, y:-0.4 },
  { code:'M', command:'moveto',                   x0:100, y0:-0.4 x:90, y:9.6 },
  { code:'L', command:'lineto',                   x0:90, y0:9.6 x:100, y:9.6 },
  { code:'V', command:'vertical lineto',          x0:100, y0:9.6, x:100, y:27  },
  { code:'V', command:'vertical lineto',          x0:100, y0:27, x:100, y:89 },
  { code:'H', command:'horizontal lineto',        x0:100, y0:89, x:23, y:89 },
  { code:'V', command:'vertical lineto',          x0:23, y0:89, y:99, x:23 },
  { code:'H', command:'horizontal lineto',        x0:23, y0:99, x:33, y:99 },
  { code:'C', command:'curveto',                  x0:33, y0:99 x1:33, y1:43, x2:38, y2:47, x:43, y:47 },
  { code:'C', command:'curveto',                  x0:43, y0:47 x1:43, y1:52, x2:48, y2:57, x:53, y:57 },
  { code:'S', command:'smooth curveto',           x0:53, y0:57 x2:63, y2:67, x:63, y:67 },
  { code:'S', command:'smooth curveto',           x0:63, y0:67 x2:53, y2:77, x:73, y:77 },
  { code:'Q', command:'quadratic curveto',        x0:73, y0:77 x1:50, y1:50, x:73, y:57 },
  { code:'Q', command:'quadratic curveto',        x0:73, y0:57 x1:93, y1:52, x:73, y:47 },
  { code:'T', command:'smooth quadratic curveto', x0:73, y0:47 x:70, y:40 },
  { code:'T', command:'smooth quadratic curveto', x0:70, y0:40 x:70, y:25 },
  { code:'A', command:'elliptical arc',           x0:70, y0:25 rx:5, ry:5, xAxisRotation:45, largeArc:true, sweep:false, x:40, y:20 },
  { code:'A', command:'elliptical arc',           x0:40, y0:20 rx:5, ry:5, xAxisRotation:20, largeArc:false, sweep:true, x:30, y:10 },
  { code:'Z', command:'closepath',                x0:30, y0:10, x:90, y:9.6 } ]

In addition to converting all commands to absolute coordinates, the makeAbsolute function ensures that:

  • Every command has x0 and y0 properties showing the start point for the command.
  • Every command has x and y properties showing the finish point for the command.
    • This makes H, V, and Z commands equivalent to an L command.

History

v1.1.0 - 2017-Jun-19

  • Add makeAbsolute(cmds).

v1.0.2 - 2017-Mar-1

  • Update package to allow latest PEGJS versions (was locked to v0.7.x).
  • Fix bug preventing parsing errors from appearing for newer PEGJS. (Issue #9)

v1.0.1 - 2014-Oct-30

  • Fix bug that prevented more than two subpaths from being returned.

v1.0.0 - 2014-Oct-12

  • Changed return values to represent each unique path command as its own object, regardless of whether the markup merged them or not. Arguments for a command (e.g. .x) are no longer in a .args array of values, but are instead part of the command object itself.

v0.0.4 - 2014-Oct-10

  • Unroll recursive grammar descriptions that could cause parsing a large path to overflow the stack.

v0.0.3 - 2014-Oct-1

  • Fix bug that prevented parsing some valid documents.

v0.0.2 - 2014-Oct-1

  • Fix parsing of numbers other than integers to work.
  • First moveto command is always absolute.
  • Additional coordinates after moveto are treated as lineto.

License

This library is released under an MIT-style license. That generally means that you are free to do almost anything you want with it as long as you give a bit of credit where credit is due. See the LICENSE file included for the actual legal limitations.

More Repositories

1

flat

🚂 Flatten/unflatten nested Javascript objects
JavaScript
1,761
star
2

disc

📈 Visualise the module tree of browserify project bundles and track down bloat.
JavaScript
1,320
star
3

envify

🔧 Selectively replace Node-style environment variables with plain strings.
JavaScript
902
star
4

colony

📈 In-browser network graphs representing the links between your Node.js code and its dependencies.
JavaScript
519
star
5

uglifyify

A browserify transform which minifies your code using UglifyJS2
JavaScript
375
star
6

vinyl-source-stream

🌀 Use conventional text streams at the start of your gulp or vinyl pipelines
JavaScript
333
star
7

glsl-noise

webgl-noise shaders ported to work with glslify
GLSL
326
star
8

smokestack

Pipe your JavaScript into a browser, logging console output in Node
JavaScript
246
star
9

boids

A fast JavaScript implementation of the boids algorithm
JavaScript
214
star
10

web-audio-analyser

A thin wrapper around the Web Audio API that takes an <audio> element and gives you its waveform/frequency data in return.
JavaScript
208
star
11

glsl-dither

Bayer matrix dithering in GLSL
C
181
star
12

game-modules

📗 A list of game-related modules and examples for writing HTML5 games with browserify
170
star
13

from2

Convenience wrapper for ReadableStream, with an API lifted from "from" and "through2"
JavaScript
131
star
14

particle-excess-demo

Simulating and rendering 262,144 particles with GLSL.
JavaScript
128
star
15

matcap

GLSL shaders for calculating/rendering Spherical Environment Maps, or "matcaps"
JavaScript
122
star
16

atom-npm-install

Automatically install and save any missing npm modules being used in the current file
JavaScript
81
star
17

s3-sync

A streaming interface for uploading multiple files to S3.
JavaScript
79
star
18

vinyl-buffer

Convert streaming vinyl files to use buffers
JavaScript
77
star
19

installify

A browserify transform that automatically installs your missing dependencies for you
JavaScript
71
star
20

gif-video

Convert a GIF image into an HTML5-ready video for considerably better file sizes
JavaScript
67
star
21

scene-tree

Modular scene graph for composing and manipulating objects in a 3D scene.
JavaScript
61
star
22

fragment-foundry

🎓 An introduction to fragment shaders and signed distance functions
GLSL
61
star
23

poly-terrain-demo

Proof-of-concept "low-poly" webgl terrain demo
JavaScript
58
star
24

scat

Pipe your javascripts straight into your browser
JavaScript
58
star
25

right-now

Get the quickest, most high-resolution timestamp possible in node or the browser
JavaScript
57
star
26

gl-gif

Quickly and easily generate looping GIFs using WebGL
JavaScript
55
star
27

vinyl-transform

Use standard text transform streams to write fewer gulp plugins
JavaScript
55
star
28

canvas-fit

Small module for fitting a canvas element within the bounds of its parent.
JavaScript
53
star
29

bezier

n-degree Bezier spline interpolation.
JavaScript
52
star
30

npm-stats

Convenience module for getting data from an NPM registry
JavaScript
51
star
31

browser-menu

A browser-friendly implementation of substack's terminal-menu
JavaScript
51
star
32

three-effectcomposer

@alteredq's EffectComposer plugin for three.js ported for use with Browserify
JavaScript
49
star
33

bistre

A command-line tool and module for printing colourful bole logs.
JavaScript
48
star
34

tap-to-start

JavaScript
48
star
35

ludum-dare-27

hurry!
JavaScript
43
star
36

glslify-live

A browserify transform that transparently enables live reloading of your shaders when using glslify.
JavaScript
42
star
37

display-tree

A JavaScript tree implementation designed to be efficiently "flattened" and sorted.
JavaScript
41
star
38

npm-me

Get a list of download counts over the last month for a particular user's packages
JavaScript
40
star
39

map-limit

async.mapLimit's functionality available as a standalone npm module
JavaScript
39
star
40

clamp

Clamp a value between two other values.
JavaScript
39
star
41

adobe-swatch-exchange

Encode/decode color palettes in Adobe's .ase format
JavaScript
38
star
42

beats

A naive but generic beat-detection module
JavaScript
37
star
43

icosphere

Generates icosphere meshes of varying levels of complexity
JavaScript
37
star
44

npm-offline

An npm registry proxy that uses your npm cache to retrieve modules, allowing for offline access to any modules you've previously installed pretty much ever.
JavaScript
37
star
45

vinyl-map

Map vinyl files' contents as strings
JavaScript
36
star
46

ndarray-pixel-sort

A JS implementation of Kim Asendorf's pixel sort glitch technique using ndarrays
JavaScript
36
star
47

komponist

A simple, yet flexible, Node client library for MPD, the hackable headless audio playback server.
JavaScript
36
star
48

png-chunks-extract

🔍 Extract the data chunks from a PNG file.
JavaScript
35
star
49

png-chunk-text

📜 Create or parse a PNG tEXt chunk for storing uncompressed text data in PNG images.
JavaScript
33
star
50

glsl-fog

Basic fog functions for GLSL
C
32
star
51

d3-grid-layout

A grid layout for d3.js
JavaScript
32
star
52

soundcloud-badge

A SoundCloud 'now-playing' badge you can just drop into browserify demos
CSS
31
star
53

topdown-physics

Basic, grid-based, 2D top-down player physics for continuous ndarrays
JavaScript
30
star
54

glsl-luma

Get the luma (brightness) of an RGB color in GLSL. Useful for converting images to greyscale
C
30
star
55

language-glsl

Atom language support for GLSL
GLSL
30
star
56

ansi-html-stream

Stream for converting terminal UTF-8 ANSI color codes into HTML
JavaScript
30
star
57

lsb

Steganography cheap trick - hide string data in the least-significant bits of an array.
JavaScript
27
star
58

post-process

A generic GLSL post-processing module for applying super-speedy GPU effects to img/video/canvas elements.
JavaScript
27
star
59

gulp-duration

Track the duration of parts of your gulp tasks
JavaScript
26
star
60

rm-modules

Recursively remove *all* node_modules directories within the chosen root directory
JavaScript
26
star
61

shallow-equals

Determine if an array or object is equivalent with another, *not* recursively
JavaScript
26
star
62

glsl-hsv2rgb

Fast GLSL conversion from HSV color to RGB
C
26
star
63

font-atlas

Populate a <canvas> element with a font texture atlas
JavaScript
25
star
64

lut

Render RGB lookup tables to a canvas element
JavaScript
24
star
65

flood-fill

A simple 2D JavaScript flood fill.
JavaScript
24
star
66

hypotrochoid

Plot hypotrochoids for spirographs with JavaScript
JavaScript
23
star
67

svg-line-curved

Generate the path attribute for a curved SVG line.
JavaScript
23
star
68

fresh-require

Bypass the require cache when requiring a module – works with both node and browserify
JavaScript
22
star
69

btoa-lite

Smallest/simplest possible means of using btoa with both Node and browserify
JavaScript
22
star
70

scroll-speed

Get the scroll speed being used on either the window or a particular element.
JavaScript
22
star
71

is-typedarray

Detect whether or not an object is a Typed Array
JavaScript
21
star
72

ndarray-continuous

Create continuous "chunked" grids/volumes with ndarrays.
JavaScript
21
star
73

ticker

Game/animation loop helper
JavaScript
21
star
74

vectors

A grab bag of vector utility functions for 2D and 3D vectors that operate on plain arrays
JavaScript
21
star
75

s3-write-stream

Pipe data straight to an S3 key of your choice
JavaScript
21
star
76

plucker

Pluck nested properties from an object
JavaScript
21
star
77

from-3d-to-2d

Take a transformation matrix like you're used to constructing with WebGL, and project arbitrary 3D points onto your 2D screen.
JavaScript
21
star
78

object-pool

Recycle objects with minimal boilerplate with an object pool
JavaScript
20
star
79

png-chunks-encode

💾 Return a fresh PNG buffer given a set of PNG chunks
JavaScript
20
star
80

moire-1

JavaScript
20
star
81

chrome-launch

Light cross-platform launcher for Google Chrome
JavaScript
20
star
82

canvas-orbit-camera

An alternative wrapper for orbit-camera that works independently of game-shell.
JavaScript
20
star
83

canvas-autoscale

A variant of canvas-fit that handles some extra magic for you: adjusting the scale of the canvas to maintain smooth framerates
JavaScript
19
star
84

soundcloud-resolve

Takes a SoundCloud URL and retrieves the relevant JSON data for that resource from the SoundCloud API
JavaScript
19
star
85

svg-line

Generate SVG paths for a line, d3-style
JavaScript
19
star
86

chrome-location

Approximates the current location of Google Chrome on your system
JavaScript
18
star
87

ecosystem-docs

Aggregate and store a collection of data for GitHub repositories, intended for use with documenting package ecosystems on npm
JavaScript
18
star
88

circular-list

Circular linked lists
JavaScript
18
star
89

district

A small tool to help you write local, namespaced packages for larger projects
JavaScript
18
star
90

module-generator

The generator script I use for fresh modules
JavaScript
17
star
91

voxel-glslgen

Push voxel.js terrain generation to the GPU using a GLSL shader
JavaScript
17
star
92

stopmotion

Combine multiple image buffer frames into a video file
JavaScript
16
star
93

tap-closer

Simple JS "transform" tool that will call window.close or process.exit when TAP output is complete
JavaScript
16
star
94

contributor-table

Automatically inject a list of your git repository's contributors into your readme.
JavaScript
16
star
95

frame-debounce

JavaScript
15
star
96

glsl-point-light

A reusable GLSL point light function
JavaScript
15
star
97

glsl-testify

Test your GLSL shaders using GLSL!
JavaScript
15
star
98

github-commit-stream

Pull a list of commits from a GitHub repository in via a stream.
JavaScript
15
star
99

fql-node

Simpler Facebook FQL queries for Node.
JavaScript
14
star
100

common-prefix

Retrieve the common prefix across multiple strings
JavaScript
14
star