如何在SVG中创建不同大小的内嵌文本?

时间:2016-10-20 12:33:22

标签: svg

在HTML中为不同的单词创建具有不同字体大小的文本非常容易。但是svg中的<text>呢?

我认为这很好地解释了我的问题:https://jsfiddle.net/4atoctra/1/

以下所有内容:

<div>
This is a text, and you can have <span style="font-size:25px">big</span> and <span style="font-size:11px">small</span> sizes easily inline.
</div>

<div style="margin-top:50px">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="none" x="0px" y="0px" width="360px" height="126px" viewBox="0 0 360 126">
<text><tspan x="150" text-anchor="middle" y="10" font-family="Tahoma" font-weight="bold" font-size="11" fill="#003863" xml:space="preserve">What about this in a &lt;svg&gt;?</tspan></text></svg>
</div>

2 个答案:

答案 0 :(得分:8)

You can just change the font-size on each tspan element?

<svg viewBox="0 0 500 100" width="500px">
  <text x="0" y="50" font-size="20">It's not <tspan font-size="30">that hard</tspan><tspan font-size="40"> to change size?</tspan></text>
</svg>

答案 1 :(得分:1)

You can use a <foreignObject> to insert HTML markup into an SVG document:

<svg width="220" height="120" viewBox="0 0 220 120">
  <rect x="10" y="10" width="200" height="100" fill="#ff9" stroke="none" />
  <foreignObject x="15" y="15" width="190" height="90">
    <div xmlns="http://www.w3.org/1999/xhtml" style="width:190px; height:90px; overflow-y:auto">This is a text, and you can have <span style="font-size:25px">big</span> and <span style="font-size:11px">small</span> sizes easily inline.
</div>
  </foreignObject>
</svg>