foliojs / fontkit

An advanced font engine for Node and the browser
1.49k stars 219 forks source link

How to output text as SVG ? #148

Open AlexandraK opened 6 years ago

AlexandraK commented 6 years ago

I'm using this code

let font = fontkit.create(buffer),
    run = font.layout(text),
    aw = 0,
    svg = run.glyphs.map((g,i) => {
      g = '<g transform="translate(' + aw + ',0)"><path d="' + g.path.toSVG() + '"/></g>';
      aw += run.positions[i].xAdvance;
      return g;
    });    

return '<svg xmlns="http://www.w3.org/2000/svg" width="' + aw + '" height="0" viewBox="0 0 ' + aw + ' 1000"><g transform="translate(0,1000) scale(1,-1)">' + svg.join('') + '</g></svg>';

but it produces a large and weird svg. It can be resized with CSS, but I would prefer more control, similar to something like what opentype.js produces. In opentype.js I pass the text and size and I get a single path, not one path for each glyph and with necessary transforms etc

Pomax commented 6 years ago

quick question: why are you setting height="0", with a viewbox that is fixed to 1000 units high? Why not pull those values from the text itself so that the SVG file is properly sized?

(track min/max x/y values as your run through run.glyphs and then use those bounding values in your svg root element to set the correct dimensions and viewbox?)

elron commented 5 years ago

I made a solution, check it out: https://github.com/elron/Font-To-SVG

Pomax commented 5 years ago

That's not "found", that's "I made". Posting it to three different issues isn't in itself objectionable, but at least be clear about what you're doing (namely, advertising your own work =)

elron commented 5 years ago

Pomax I did not create the full answer, I found someone else's but made it clearer. anyway I changed it... Honestly I just posted it to help people who need answer so IMO it doesn't matter who created the answer.

Pomax commented 5 years ago

But it's a repo on your account. The way open source works, that kind of makes it yours. So own that. You made a thing, even if it's based on something else. You didn't suddenly find it on your own account, that'd be magical =P

elron commented 5 years ago

Haha okay. Next time I'll say I made something not found something.