in reply to SVG text width calculation

Use the attribute text-anchor="middle" instead of computing the width yourself (which is hard to do as you usually wouldn't easily get at the individual glyphs' widths of the particular font being used).

Here's an example that centers text above a rectangle:

<?xml version="1.0" encoding="UTF-8"?> <svg version="1.2" width="100%" height="100%" viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"> <g transform="translate(100 100)"> <rect width="200" height="50" x="-100" y="10" fill="lightyellow"/> <text text-anchor="middle">Some centered text</text> </g> </svg>

(tested with Firefox 3.6.8 and Opera 10.63)

Replies are listed 'Best First'.
Re^2: SVG text width calculation
by moritz (Cardinal) on Dec 29, 2010 at 21:45 UTC

    This is indeed the best solution, though one has to be aware that client support for text anchors isn't generally very good - last I tried inkscape didn't recognize it.

    While SVG is a very nice format, and easy to generate, client side support is as unreliable as web programming in the days where you had to support IE 4 to 6 and all the "normal" browsers too. (I've ranted about this before).

    Another possible approach (but clearly inferior to text-anchor) is to estimate the length of the rendered text (for example with help of Font::TTFMetrics), and then fixing the length to the calculated value with the textLength attribute. But then again this often results in ugly output, and the client support for textLength is equally bad.

Re^2: SVG text width calculation
by Anonymous Monk on Dec 29, 2010 at 22:38 UTC
    Thanks! That did the trick.