What is the problem of word-wrapping?
An existing string:
Li Qingzhao's cut plum, have you read it?
body Add an svg element to the size as follows:
var width =;
var height =;
var svg = d3.select ("Body")
. Append ("SVG")
. attr ("width", width)
Then add the text, with the text elements, such code we are very familiar with:
var text = svg.append ("text").
attr ("x").
attr ("Y", m).
attr ("Font-size")
. attr (" Font-family "," SimSun ")
The results are as follows:
As you can see, although the contents of the text element label have an entire string, because svg the width is only 300, it cannot display such a long string, so the extra part is not visible.
What to do? Nature is to change lines.
Second, add Tspan child elements in text
Text in SVG does not support wrapping automatically and needs to be implemented manually. One way is to use tspan labels.
tspan is written in text and exists as its child element. When you set the Text property, there dy is a property that represents the y relative displacement of the axis, which is usually a value of dy 10px, 1em, which is in the em behavior unit.
In this way, we can text add more than one tspan , each representing a row. Each tspan attribute is given a 1em value (that is, one row). This way, the text will be displayed line by row.
The SVG code is:
<text x= "A" y= "font-size=" font-family= "SimSun" > <tspan x= "dy=
" "1em" > Night to dream of returning to the hometown </tspan >
<tspan x= "dy=" 1em "> Xiao Xuan Window </tspan>
<tspan x=" dy= "1em" > is dressing </tspan>
Be aware that tspan the X attribute in is necessary to indicate that the next line also x = 30 starts at the beginning.
Three, D3 code how to write
For the first section of the string, first svg add an text element to it, but do not set its contents.
var str = "In the cloud who sent the brocade book, The Wild Goose Word back, the month fills the West building";
var text = svg.append ("text").
attr ("x"). attr ("Y", m).
attr ("Font-size", 30)
To use a JavaScript string split to str fragment:
Use a comma as a separator, divided into paragraphs. The output is an array, and the items in the array are substrings. The value of the STRs is:
OK, next is the key, text bind the data in the element and add the strs same element as the length tspan . Then, assign a x value to it and the dy property, and then specify the string contents.
The code is as follows:
Text.selectall ("Tspan")
. Data (STRs).
enter ().
Append ("Tspan").
attr ("x", Text.attr ("x")
). attr ("Dy", "1em")
. Text (function (d) {return
D;
The results are as follows:
To this we are basically completed, the following to give you a complete sample code, there is a need to refer to.
The full instance code is as follows
Summarize
The above is the entire content of this article, I hope the content of this article for everyone to learn or use d3.js can help, if you have questions you can message exchange.