How can I make text automatically scale down in an SVG?

三世轮回 提交于 2019-12-06 19:41:25
Phrogz

You have text of arbitrary line length (in terms of characters) and you want to scale it to fit inside a fixed amount of space? The only way I can think of to rescale text to a fixed size is to place it inside an svg element and then scale the SVG to that size:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <title>Resizing Text</title>
  <defs>
    <svg id="text-1" viewBox="0 0 350 20">
      <text id="text-2" x="0" y="0" fill="#000" alignment-baseline="before-edge">It's the end of the world as we know it, and I feel fine!</text>
    </svg>
  </defs>
  <rect x="500" y="100" width="200" height="40" fill="#eee" />
  <use  x="510" y="110" width="180" height="20" xlink:href="#text-1" />
</svg>

However, as seen above, the viewBox on the encapsulating svg element needs to be set to the width of the text, which you presumably don't know.

If you're referencing this SVG inside a user agent with scripting available (e.g. a web browser) then you could easily write a script to capture the width of the text or tspan element and set the viewBox accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!