如何在 D3.js 中动态显示多行文本? [英] How to dynamically display a multiline text in D3.js?
问题描述
我需要使用 D3.js 在 SVG:Text 中显示多行文本.
I need to display a multiline text in a SVG:Text using D3.js.
示例数据如下所示,我想在单个节点下为每个作者显示所有"标题",而不是作为强制方向布局中的单个节点.
The sample data looks as follows and I want to display "all" the "titles" under a single node for every author and not as an individual node in a force directional layout.
样本数据
{
{"author":"Author1", "group":"fiction", "books" : [
{"title":"Book Title1", "rating":3},
{"title":"Book Title2", "rating":4}
]},
{"author":"Author2", "group":"non-fiction", "books" : [
{"title":"Book Title3", "rating":3},
]}
}
SVG:text 只需要一个文本条目并显示在一行中,所以我添加了更多文本并调整dy"?或收回节点信息并替换?
SVG:text takes only one text entry and displays in a single line, so I have add more text and adjust the "dy"? or retractively collec node information and replace?
感谢您的提示.
推荐答案
您有以下选择.
- 正如您所提到的,您可以添加多个具有适当间距的
text
元素. - 您还可以在一个
text
元素中使用多个tspan
元素来达到相同的效果.同样,您必须自己设置间距. - 您可以使用
foreignObject
嵌入一个合适的 HTML 元素(例如div
),它将为您处理换行、间距等.有关示例,请参见例如此处.
- You can, as you've mentioned, add more than one
text
element with the appropriate spacing. - You can also use multiple
tspan
elements within atext
element to the same effect. Again, you would have to set the spacing yourself. - You can use
foreignObject
to embed a suitable HTML element (e.g. adiv
) that will take care of the line breaking, spacing etc. for you. For an example of that, see e.g. here.
我会选择 HTML 嵌入选项,除非您有特定的理由不这样做.它使实际的文本格式设置比其他选项容易得多.
I would go with the HTML embedding option unless you have a specific reason not to. It makes the actual text formatting so much easier than the other options.
这篇关于如何在 D3.js 中动态显示多行文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!