How to break text in 2 lines in d3.js?

Member

by lily , in category: Javascript , a year ago

How to break text in 2 lines in d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 6 months ago

@lily 

To break text into 2 lines in D3.js, you can use the tspan element within a SVG text element. Here is an example code snippet that demonstrates how to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var svg = d3.select("body")
  .append("svg")
  .attr("width", 200)
  .attr("height", 100);

var text = svg.append("text")
  .attr("x", 100)
  .attr("y", 50)
  .style("text-anchor", "middle")
  .text("Hello World");

text.append("tspan")
  .attr("x", 100)
  .attr("dy", 20)
  .text("Second Line");


In this code snippet, we first create an SVG element and append a text element to it. We set the x and y coordinates of the text element to position it in the SVG. We also set the text-anchor style to "middle" to center the text.


Next, we use the append method to add a tspan element to the text element. We set the x coordinate to the same value as the text element and use the dy attribute to move the second line down by 20 units. Finally, we set the text content of the tspan element to "Second Line", which will display it as the second line of text.


You can adjust the positioning and styling of the text and tspan elements to suit your needs.