SVG, текст, шрифт с фиксированной шириной/высотой

В Windows Добавляет Взаимно блокируемый *** Exchange ***, как, гарантируют, будет атомарным.

7
задан Pierre 13 November 2009 в 22:26
поделиться

1 ответ

The size of a font determines its height, not its width; and characters are rarely square.

So as far as I know, there's no way to determine the width of even monospace text reliably through CSS.

Well, CSS3 has the ch unit, which is the width of the 0 character. That would work for monospace text. But it's not supported in SVG.

You could just set a fixed width in pixels, of course. A width of 300 pixels works for me. But then if someone else uses a different monospaced font that fixed width could be off. If you add the font-family:monospace;font-size:100px; on the too, you can set the width of the rectangle in ems. But I don't think that's any more reliable.

You can, however, use scripting. You can use getComputedTextLength() to get the text length of a text element:

<script type="text/javascript">
document.getElementById('rect').setAttribute(
    'width',
    document.getElementById('text').getComputedTextLength()
);
</script>

Adding that at the end of your SVG (and adding the appropriate element IDs) works in Opera 10, Firefox 3.5 and Safari 4.0, at least.

And while you're at it, you could use getBBox() too, to get the text element's bounding box so you can set the height of the rectangle to match the font size too, in case you ever decide to change the font size.

8
ответ дан 7 December 2019 в 05:24
поделиться
Другие вопросы по тегам:

Похожие вопросы: