Sergey Rudenko
Sergey Rudenko

Reputation: 9227

D3,js path data string - should I parse it or there is an API for it?

learning D3 now and I have a use case where I have the following code:

let length = (3 + ((15000000 / 1500) % 8)) | 0;
let polygon = d3
      .radialLine()
      .angle((_, i) => (i / length) * 2 * Math.PI)
      .curve(d3.curveCardinalClosed)
      .radius(() => 150);
let path = polygon({ length });

So the 'path' variable does give me the "d" attribute as a string.

Now for the implementation, I have in mind I need the same path data in more of a "parseable" format.

Question - surely I can just parse the string right away (there are many parsers out there to turn d path string to an array etc), but I am just wondering if there is d3 embedded method for that? so that I do not have to use additional parser?

Upvotes: 0

Views: 392

Answers (1)

Alex L
Alex L

Reputation: 4241

I don’t think there’s one built into d3 but if there is I’d love to hear about it!

You could use this npm package:

https://www.npmjs.com/package/svg-path-parser

Or the browser’s built in path.getPathData() New API (which replaces the old path.pathSegList)

Sadly not implemented in all browsers yet so we can use a polyFill for now and hopefully it will be broadly supported soon.

Example:

const route = document.querySelector('#route');
console.log(route.getPathData()); //.pathSegList(); .getPathData();
<svg viewBox="0 0 500 500">
    <path stroke="grey" fill="none" id="route" d="M50,25 75,55 Q75,75 35,75 z" />
</svg>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/path-data-polyfill.min.js"></script>

Upvotes: 1

Related Questions