Just a collection of svg javaScript helpers based on the official draft of the SVG Paths specification introducing the getPathData()
and setPathData()
methods.
Currently getPathData()
is not natively supported by any major browser, thus you need a polyfill like Jarek Foksa's path-data-polyfill.
Include the aforementioned polyfill by Jarek Foksa either by downloading the current version or via cdn like so:
<script src="https://cdn.jsdelivr.net/npm/path-data-polyfill@latest/path-data-polyfill.min.js"></script>
getPathData()
parses an existing SVG element to an array of command objects like this:
<svg>
<path id="path1" d="M 0 50 L 50 50 L 50 100 L 0 100 z" />
</svg>
let pathData = path1.getPathData();
returns this array:
[
{ type: "M", values: [0, 50] },
{ type: "L", values: [50, 50] },
{ type: "L", values: [50, 100] },
{ type: "L", values: [0, 100] },
{ type: "Z", values: [] }
];
reapply to path d
attribute
path1.setPathData(pathData);
<script src="https://cdn.jsdelivr.net/gh/herrstrietzel/svgHelpers@main/js/pathData.relativeAbsolute.min.js"></script>
- pathData
- decimals (optional): round to floating point decimals (-1 disables rounding)
- unlink (optiona)l: creates a seperated pathData copy
All relative
let pathData = path.getPathData();
let pathDataRelative = pathDataToRelative(pathData);
path1.setPathData(pathDataRelative);
All absolute
let pathData = path.getPathData();
let pathDataAbsolute = pathDataToAbsolute(pathData);
path1.setPathData(pathDataAbsolute);
All Shorthand commands V
, H
, S
, Q
will be converted to their longhand counterparts
L
, C
, Q
.
<script src="https://cdn.jsdelivr.net/gh/herrstrietzel/svgHelpers@latest/js/pathData.shorthands.min.js"></script>
- pathData
- decimals (optional): round to floating point decimals (-1 disables rounding)
let pathData = path.getPathData();
let pathDataLonghands = pathDataToLonghands(pathData);
path.setPathData(pathDataLonghands);
Will try to apply shorthand commands - if applicable.
let pathData = path.getPathData();
let pathDataShorthands = pathDataToShorthands(pathData);
path.setPathData(pathDataShorthands);
- parseDtoPathData(d);
- setPathDataOpt(path, pathData, decimals=-1);
- roundPathData(pathData, decimals=-1)
// parse to pathData array
let d = path.getAttribute('d');
let pathData = parseDtoPathData(d);
// set path `d` - apply rounding
setPathDataOpt(path, pathData, 3);
- path element
d
attribute - normalize (optional): Boolean
let d = path.getAttribute('d');
let pathData = parseDtoPathData(d, true);
Normalize option converts all commands like the official getPathData({normalize:true})
:
- all absolute
- convert shorthands to longhand notation
- convert quadratic
Q
and arcA
commands to cubicC
This script included helper functions from
- pathData.relativeAbsolute.js
- pathData.shorthands.js
<script src="https://cdn.jsdelivr.net/gh/herrstrietzel/svgHelpers@latest/js/pathData.parseAndConvert.js"></script>