How to dynamically display a multiline text in D3.js?

You have the following options.

  • 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.

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.

Leave a Comment