您可以在 SVG 模板中添加一个脚本,该脚本在 SVG 加载时调用,并使用 getComputedTextLength() 调整字体大小。这是一个有点老套的解决方案,但它似乎有效。
这是一个简单的示例,它在其中绘制一个框和一些文本。无论文本有多长,都应调整文本大小以始终适合框(至少到点):
要在加载 SVG 时调用代码,请在 SVG 标记中包含 onload="int(evt)"。
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="400" height="80"
onload="init(evt)">
然后是实际的脚本:
<script type="text/ecmascript">
<![CDATA[
function init(evt)
{
if ( window.svgDocument == null )
{
svgDocument = evt.target.ownerDocument;
}
maximum_length = 300;
my_text = svgDocument.getElementById('text-to-resize');
for (var font_size=55; font_size>0; font_size--)
{
if(my_text.getComputedTextLength() < maximum_length){break;}
my_text.setAttributeNS(null, "font-size", font_size);
}
}
]]>
</script>
我只是使用了一个 for 循环来减小字体大小,直到文本长度小于指定的最大值;我确信有更好的方法来调整文本大小。
最后是实际的文本和框:
<rect id="rect1" x="20" y="10" width="320" height="50" fill="white" stroke="black"/>
<text id="text-to-resize"
text-anchor="middle"
x="170" y="50"
font-family="Times New Roman" font-size="55">
whatever text
</text>
</svg>
如果您更改文本,字体大小应更改以适合框内。您可能还想更改 x 和 y 值以正确居中文本。