如何确定 SVG 文本框宽度,或在“x"字符后强制换行? [英] How to either determine SVG text box width, or force line breaks after 'x' characters?
问题描述
我正在使用 Raphael 库创建一个 SVG 文本框,并使用从 XML 文档中提取的动态字符串填充它.
I'm creating an SVG text box using the Raphael library, and filling it with a dynamic string which is extracted from an XML document.
有时,这个字符串比我放置文本框的画布长,所以我需要限制框的宽度,这本身会强制换行(我找不到任何可能的证据) 或确保在一定数量的字符后插入一个 ' ' 换行符.
Sometimes, this string is longer than the canvas I am placing the text box on, so I need to either limit the width of the box which will itself force the line breaks (I can't find any evidence of this being possible) OR ensure that a ' ' line break is inserted after a certain amount of characters.
那么 (1) 这是最好的选择吗?以及 (2) 我将如何做到这一点?
So (1) is this the best option? And (2) how would I do this?
推荐答案
没有用于文本换行的属性,但是您可以使用一个简单的技巧.一次向文本对象添加一个单词,当它变得太宽时,添加换行符.您可以使用 getBBox() 函数来确定宽度.基本上,您可以模拟老式打字机.下面是一些可以为您执行此操作的代码示例.你可以很容易地把它变成一个简单的函数,它接受文本和宽度.
There isn't an attribute for text wrapping, but there is a simple trick you can use. Add one word at a time to a text object and when it gets too wide, add a line feed. You can use the getBBox() function to determine the width. Basically, you emulate an old fashioned typewriter. Here is a sample of some code that will do this for you. You could easily turn this into a simple function that takes the text and a width.
var r = Raphael(500, 500);
var t = r.text(100, 100).attr('text-anchor', 'start');
var maxWidth = 100;
var content = "Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate. ";
var words = content.split(" ");
var tempText = "";
for (var i=0; i<words.length; i++) {
t.attr("text", tempText + " " + words[i]);
if (t.getBBox().width > maxWidth) {
tempText += "
" + words[i];
} else {
tempText += " " + words[i];
}
}
t.attr("text", tempText.substring(1));
这篇关于如何确定 SVG 文本框宽度,或在“x"字符后强制换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!