D3js: How to convert SVG text to a path?

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

So, when I understand the generated svg, I can save my texts.

+5
source share
2 answers

In JavaScript (d3 or any other tool) there is no way to access vector path information about the shape of individual letters in system or web fonts. This is the requested feature for SVG 2, but there are no solid suggestions as to how it will work.

Raphael method described in the questions connected with Lars Kottoffom uses a font object that has already been converted to JavaScript, using the font generator tool Cufon . Unfortunately, Cufon was designed for the old IE VML, not SVG, so you will need to add an extra conversion (or use Raphael) to convert to SVG path data.

To work with SVG, it can be just as simple to use a common tool to convert fonts to SVG fonts, then extract the glyph data and convert it (to the desired size and flip the y axis). Alternatively, if you are running a server, you can explore the use of a low-level graphics library such as Cairo, which can convert text to a path. Unfortunately, browser support for SVG fonts is so poor that you cannot use it to embed font data directly. (Even if you have rights to distribute the font, but do not use web fonts for other reasons).

Update: Mentioning Inkscape in the comments reminded me that Inkscape also has a command line interface for converting / exporting SVG files . You can use it in the server workflow; text-to-path is one of the export options. You will need to figure out how to configure it so that the Inkscape program on your server has access to the full font, and then pass the SVG created by your d3 procedure through Inkscape, with parameters such as:

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

The only text-to-image option in the DOM is an HTML canvas; You can write on canvas and then capture image data. But it will be a PNG image, not a vector.

However, I would also like to suggest that you consider whether you really need the exact form of the letters in a particular font, and if you lose the functionality, accessibility, and SEO benefits that come from using text as text.

+14
source

There is a node module called text-to-svg that states this:

Convert text to SVG path without built-in dependencies.

Example

 const TextToSVG = require('text-to-svg'); const textToSVG = TextToSVG.loadSync(); const attributes = {fill: 'red', stroke: 'black'}; const options = {x: 0, y: 0, fontSize: 72, anchor: 'top', attributes: attributes}; const svg = textToSVG.getSVG('hello', options); console.log(svg); 
+2
source

Source: https://habr.com/ru/post/1205631/


All Articles