linebender / piet

An abstraction for 2D graphics.
Apache License 2.0
1.23k stars 95 forks source link

Improve text position in SVG. #536

Closed derekdreery closed 1 year ago

derekdreery commented 1 year ago

Because SVG uses the baseline to position text, while we use the top-left of the text, we need to convert between the two.

Before this PR, the whole font height was used, which pushes the text down too far.

After this PR, we tell SVG to use the top of the ascender as our anchor point (dominant-baseline: hanging), with an additional fiddle factor of 0.04 * font height because we actually want the top of the line, not the ascender. The fiddle factor was worked out by eye looking at the default sans-serif font, comparing the svg to a png generated by piet-cairo.