你可以在SVG模板中添加一个脚本,当SVG加载时调用它,并使用
getComputedTextLength()
来调整字体大小。这是一个有点hacky的解决方案,但似乎可行。
下面是一个快速示例,它绘制了一个框和一些文本。文本应该被调整大小以适应框的大小,无论它有多长(至少到某个程度):
要在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值以正确居中文本。