dbuenzli / vg

Declarative 2D vector graphics for OCaml
http://erratique.ch/software/vg
ISC License
91 stars 12 forks source link

how to measure the text #6

Closed samoht closed 10 years ago

samoht commented 10 years ago

Just to remember @talex5 remark on the mirage list

I almost had it working with Vg, but there seemed to be no way to measure the text, which is needed to place the labels, so I ended up using HTML canvas directly. As it turned out, that API was a better fit for me anyway (being more similar to Cairo's API).

dbuenzli commented 10 years ago

Vg is a low-level rendering API with multiple rendering backends and a glyph API.

Measuring text means transforming text to sequences of positioned glyphs and is not in the scope of Vg. This should be delegated to another module (e.g. an OpenType layout engine, think pango or harfbuzz).

If you are not dealing with complex scripts and want to remain backend independent you can however use Otfm to access a font's metrics and do a toy text layout engine with kerning, see for example this example in Vg's distribution. It was part of Vz's plans to provide such a toy text engine as a temporary solution since measuring text is indeed needed for label placement.

One additional problem is that the canvas only provides a text api and no glyph api (see the canvas backend docs). This means that in the canvas we have access to the powerful browser text layout engine but this is something we don't have for example in the PDF backend where you have to layout the glyphs by yourself. So there could be the problem of discrepancy between the way you measure text and the way the browser measures text and the discrepancy between the layout you do for PDF and the layout the canvas does for you.

Now if you are dealing only with the Canvas backend. You can use the measureText canvas API to measure the text you are about to render. The idea would be to create a small abstraction that uses a hidden separate canvas context to which you can ask to measure a string of text whose glyphs you are about to cut.

I'm closing since it's not in scope of Vg but feel free to continue the discussion or ask any further question.