D3js : How to convert svg text to path?

前端 未结 2 1455
攒了一身酷
攒了一身酷 2021-02-14 10:23

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.

相关标签:
2条回答
  • 2021-02-14 10:54

    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.

    0 讨论(0)
  • 2021-02-14 11:12

    There is a node module called text-to-svg that claimed to do so:

    Convert text to SVG path without native 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);
    
    0 讨论(0)
提交回复
热议问题