SVG Scaling Text to fit container

2019-01-13 18:04发布

This is likely a very simple question, but how do I get text in SVG to stretch to fit its container?

I don't care if it looks ugly from being stretched too long or high, but it needs to fits its container and be as big as possible.

Thanks

3条回答
The star\"
2楼-- · 2019-01-13 18:38

If you really don't care that the text gets ugly, here's how to fit unknown length text into a known width.

<svg width="436" height="180"
    style="border:solid 6px"
    xmlns="http://www.w3.org/2000/svg">
    <g>
        <text y="50%" textLength="436" lengthAdjust="spacingAndGlyphs">UGLY TEXT</text>
    </g>
</svg>

enter image description here

查看更多
虎瘦雄心在
3楼-- · 2019-01-13 18:40

Maybe this could work for you. You'd have to tweak the values, but it does resize when the parent div resizes. Here's my dabblet example. It works similarly to fittext.js

I used the ‘viewBox’ & ‘preserveAspectRatio’ attributes.

<svg><text x="50%" y="50%" dy=".3em">Look, I’m centered!</text></svg>
<svg viewBox="-50 -50 100 100" preserveAspectRatio="xMidYMid meet"><text font-size="16" dy=".3em" >I’m also resizeable!</text></svg>

other resources I looked at:

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-13 18:58

Here is what I have come up with... Its similar to what other people have posted, but I think it resizes and scales nicely. This code will add spacing to any text roughly between 10-25 characters to make it fill the entire width of its parent. If you need longer or shorter text, just adjust the viewBox width and textLength attributes.

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox='0 0 300 24'>
<text textLength='290' lengthAdjust="spacing" x='5' y="14" >
    Some Unknown Text that is resizing
</text>
</svg>

查看更多
登录 后发表回答