D3js : How to convert svg text to path?

Hugolpz picture Hugolpz · Oct 27, 2014 · Viewed 13.7k times · Source

Is there a D3.js way to convert a text element into a path element?

So when I grasp the generated svg, I could keep my the texts shapes.

Answer

AmeliaBR picture AmeliaBR · Jan 31, 2015

There is no way in JavaScript (d3 or any other tool) to access the vector path information about the shape of individual letters in system or web fonts. It's a requested feature for SVG 2, but there are no firm proposals for how it would work.

The Raphael method described in the question linked by Lars Kotthoff uses a font object that has already been converted to JavaScript, using the Cufon font generator utility. Unfortunately, Cufon was designed for the old IE VML language, not SVG, so you would need to add an extra conversion (or use Raphael) to convert to SVG path data.

For working with SVG, it might be just as easy to use a general font-converter tool to convert to SVG fonts, then extract the glyph data and transform it (to the correct size and to flip the y-axis). Alternately, if you're working on a server you could look into using a low-level graphics library such as Cairo which can do text-to-path conversion. Unfortunately, SVG font support in browsers is so poor that you can't use it to embed the font data directly. (Even assuming you had the rights to distribute the font, but were not using web fonts because of other reasons).

Update: The mention of Inkscape in the comments reminded me that Inkscape also has a command-line interface to convert/export SVG files. You may be able to use it in a server workflow; text-to-path is one of the export options. You'd have to figure out a way to set it up so the Inkscape program on your server has access to the complete font, and then shuttle the SVG created by your d3 routine through Inkscape with options like:

inkscape TEMP.FILENAME --export-plain-svg=FILENAME --export-text-to-path

The only text-to-image option in the DOM is HTML canvas; you can write on the canvas and then grab the image data. But that would be a PNG image, not a vector.

However, I would also urge you to consider whether you really need the exact shapes of the letters in a specific font, and if it is worth losing the functionality, accessibility, and SEO benefits that come from using text as text.