foliojs / fontkit

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

How to create a text SVG of a specified size? #220

Closed StringKe closed 4 years ago

StringKe commented 4 years ago

font.layout("hello").glyphs[0].path.toSVG() It's too big. How do I set the font size and generate SVG?

Pomax commented 4 years ago

What do you mean "it's too big"? SVG is unitless: a 1000x1000 SVG is not "pixels", it's just "1000 units, proportional to the unit value that the vectors use". Hence the Scalable Vector Graphics name.

You can fit an SVG to any size you need by simply scaling the whole thing to fit whatever box it needs to go into (via CSS, typesetting box commands, etc).

StringKe commented 4 years ago

What do you mean "it's too big"? SVG is unitless: a 1000x1000 SVG is not "pixels", it's just "1000 units, proportional to the unit value that the vectors use". Hence the Scalable Vector Graphics name.

You can fit an SVG to any size you need by simply scaling the whole thing to fit whatever box it needs to go into (via CSS, typesetting box commands, etc).

For example, how wide is a 12px pixel font?

Pomax commented 4 years ago

That question literally has no answer in real typography other than "measure it after typesetting it" (e.g. what typesetting software like LaTeX or InDesign do). Font size says nothing about "how wide" text is. It technically doesn't even say anything about "how high" your text will be. Your font size is effectively a baseline-to-baseline metric, and the font gets consulted on how best to scale things to make the baseline distance match your requested "font size".

To be more preceise about that, as fonts rely on a unitless coordinate system, the only "size" the encode is the em quad size (defining the quad as either 1000x1000 or 2048x2048 units, depending on the OpenType flavour) so if you ask Fontkit to export text as SVG, you're going to get vector graphics back using the font's native coordinate values, and you then get to scale that so that it fits into whatever you need it to fit in.

If the SVG is too big, scale it down. That's exactly what SVG is for. However, note that if you want things scale to tiny sizes, like 12pt, you probably don't want SVG at all. You want to tell the font to render itself to that specific size, because it might have bitmap strike data that is optimized for the exact point/pixel size you need the text shaped at, because scaling down to small point sizes is really, really, REALLY hard and the easiest way around the problem of scaling is to just say "don't bother. Here's the bitmap, we -the people who made this font- already took the time to determine which bitmap looks closest to what it should look like".

StringKe commented 4 years ago

I see that the font size can be set in pdfkit. I tried to find the corresponding method in this package, but there was no result.