d3plus-shape
Version:
Fancy SVG shapes for visualizations
42 lines (37 loc) • 1.62 kB
JavaScript
import pointDistance from "./pointDistance";
import shapeEdgePoint from "./shapeEdgePoint";
var pi = Math.PI;
/**
@function path2polygon
@desc Transforms a path string into an Array of points.
@param {String} path An SVG string path, commonly the "d" property of a <path> element.
@param {Number} [segmentLength = 20] The lenght of line segments when converting curves line segments. Higher values lower computation time, but will result in curves that are more rigid.
@returns {Array}
*/
export default (function (path) {
var segmentLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20;
var poly = [],
regex = /([MLA])([^MLAZ]+)/ig;
var match = regex.exec(path);
while (match !== null) {
if (["M", "L"].includes(match[1])) poly.push(match[2].split(",").map(Number));else if (match[1] === "A") {
var points = match[2].split(",").map(Number);
var last = points.slice(points.length - 2, points.length),
prev = poly[poly.length - 1],
radius = points[0],
width = pointDistance(prev, last);
var angle = Math.acos((radius * radius + radius * radius - width * width) / (2 * radius * radius));
if (points[2]) angle = pi * 2 - angle;
var step = angle / (angle / (pi * 2) * (radius * pi * 2) / segmentLength);
var start = Math.atan2(-prev[1], -prev[0]) - pi;
var i = step;
while (i < angle) {
poly.push(shapeEdgePoint(points[4] ? start + i : start - i, radius));
i += step;
}
poly.push(last);
}
match = regex.exec(path);
}
return poly;
});