Skip to content

Usage Examples

thednp edited this page Oct 4, 2024 · 14 revisions

Typescript / ES6+ Usage

Import, initialize and call multiple instance methods, or return the values right away.

Example

// import the constructor
import SVGPathCommander from 'svg-path-commander'

let pathString = 'M0 0l50 0l50 50z';

// initialize
let mySVGPCInit = new SVGPathCommander(pathString);
/* 
returns => {
  pathValue: 'M0 0l50 0l50 50z',
  segments: [ ['M',0,0], ['l',50,0], ['l',50,50], ['z'] ],
  round: 3,
  origin: [50, 25, 125]
}
*/

// direct access to methods
let mySVGPCInit = new SVGPathCommander(pathString).flipX().toString();
// returns => "M100 50L50 0L0 0z"

Node.js

// import the constructor
const SVGPathCommander = require('svg-path-commander');

let pathString = 'M0 0l50 0l50 50z';

// initialize
let mySVGPCInit = new SVGPathCommander(pathString);

// or do whatever you want, perhaps you're a font creator?
let mySVGPCString = new SVGPathCommander(pathString)
                  .flipX()
                  .optimize()
                  .toString();

Main Methods Examples

// reuse same init object to call different methods
// for instance convert to ABSOLUTE and return the initialization object
mySVGPCInit.toAbsolute()

// or convert to RELATIVE and return the string path directly
mySVGPCInit.toRelative().toString()

// or convert to CURVE and return the string path directly
mySVGPCInit.toCurve().toString()

// reverse and return the string path
mySVGPCInit.reverse().toString()

// ONLY reverse subpaths and return the string path
// if the shape has no sub-path, this call will produce no effect
mySVGPCInit.reverse(1).toString()

// converts to both absolute and relative then return the shorter segment string
mySVGPCInit.optimize().toString()

// or return directly what you need
// reverse subpaths and return the optimized pathString
let myReversedPath = new SVGPathCommander(pathString).reverse(1).optimize().toString()

// flip the shape vertically and return the pathString
mySVGPCInit.flipX().toString()

// apply a skew transformation and return the pathString
mySVGPCInit.transform({skew:25}).toString()

Instance Options Example

// disable rounding values
let mySVGPath = new SVGPathCommander('M0 0L0 0', { round: false })

// OR set a certain amount of decimals
let mySVGPath = new SVGPathCommander('M0 0L0 0', { round: 9 })

// Apply a 45deg rotation on Z axis and use a custom transform origin 
let mySVGPath = new SVGPathCommander( 'M0 0L50 0' )
                    .transform({ rotate:[0,0,45], origin: [25,25] }) 

Apply Transform To Path Commands

You can either call the SVGPathCommander methods flipX() or flipY() to perform a quick transformation or set custom functions, in which case you can provide a transformObject Object

2D Transformation Example

// define properties you want to transform
let transformObject = {
  scale: 0.3,
  translate: 20,
  rotate:45,
  skew:20
}

let myPathString = new SVGPathCommander('M0 0L0 0')
                      .transform(transformObject)
                      .toString()

3D Transformation Example

The transformObject can also set the transform-origin required for the transformation, if origin property is not set, by default 50% 50% of the shape's bounding box is used; absolute values relative to a parent SVGElement are expected.

// define properties to apply a transformation for 
// also provide a transform origin with the "origin" Object property
let transformObject = {
  origin: [205,205,205], // transform origin assumes the shape bounding box is 410 wide and 410 tall
  scale: [0.3,0.3,0.3],  // all axes scale
  translate: [20,0,0],   // translateX
  rotate:[0,0,45],       // rotateZ
  skew:[20,0]            // skewX
}

let myPathString = new SVGPathCommander('M0 0L0 0')
                      .transform(transformObject)
                      .toString()

For simplicity reasons and other considerations, we've decided not to include support for axis specific transform functions like rotateX or scaleY, since DOMMatrix and WebKitCSSMatrix APIs both support shorthand functions and would not make sense to just alocate more memory for aliases.

Determine Shape Draw Direction

When reversing path strings, you might want to know their draw direction first:

Example

import getDrawDirection from 'svg-path-commander/src/util/getDrawDirection.js'

// init
let shapeDrawDirection = getDrawDirection(pathString)
// => returns TRUE if shape draw direction is clockwise or FALSE otherwise

Keep in mind that paths with sub-paths may skew your result, you may want to split them and perform this check on each.

Advanced Usage

In most cases, you can import only the tools you need, without importing the entire library. All utilities are modules with proper TypeScript definitions.

import pathToAbsolute from 'svg-path-commander/src/convert/pathToAbsolute.js'
import pathToString from 'svg-path-commander/src/convert/pathToString.js'

let mySVGAbsolutePath = pathToString(pathToAbsolute(pathString))

Most important of these tools are already exported to global and are part of the Static Methods.

Convert Shape To Path

You can convert any shape to <path> via the SVGPathCommander.shapeToPath() static method.

// convert a shape to `<path>` and transfer all non-specific attributes
const circle = document.getElementById('myCircle');
SVGPathCommander.shapeToPath(circle, true);

// alternatively you can create <path> from specific attributes
const myRectAttr = {
  type: 'rect',
  x: 25,
  y: 25,
  width: 50,
  height: 50,
  rx: 5
};

const myRectPath = SVGPathCommander.shapeToPath(myRectAttr);
document.getElementById('mySVG').append(myRectPath);
Clone this wiki locally