您可以在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值以正確地居中文本。
參見:http://stackoverflow.com/questions/2938779/svg-scaling-text-to-fit-container – 2012-08-04 17:32:18