且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 D3.js 中动态显示多行文本?

更新时间:2023-08-30 21:00:22

您有以下选择.

  • 正如您所提到的,您可以添加多个具有适当间距的 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 a text 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. a div) 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.