We can easily add text element in the SVG with help of text element and by default browser put the text coordinate of x, y to zero, the text will appear on the top left of the browser and we may not be able to see the text.
What we are learning here
- SVG text element attribute.
- Positioning our text element in SVG
- Use of tspan in text
We can add the text in SVG as svg.append(“text”).text(“Hello World”). In above code all word begins at the newx that is 400px, we will change the alignment of each word and we want to line up text item in the exact center of another element say a rectangle. In D3 we can’t do adding text to another svg shape and can’t apply alignment to the middle, start, and end. In other words, we can’t add text to a rectangle, circle or any other SVG element. What we can do is add one element one top of another and position them in a similar way.
Screen shot of our above code
As text is aligned default by the browser at the bottom left of text element or item. In above picture, we can see black line start at the bottom of word start and similar end at the bottom of a word end. By default, our text is aligned vertically by the browser at the bottom of the text. We can change the vertical alignment with two attributes in D3. But alignmentBaseLine is not working properly in the Firefox and we can use dominantBaseLine to change the vertical alignment in D3. We can see the second picture where the line had stay in the same position it was before but the text had shifted down.
Text alignment in the SVG
We can align our text position in SVG with help of two Attribute.
Text-anchor – To align text horizontal as star, middle, and end.
Dominant-box – To align text in vertical.
In the second example below we can see that we can align the text on top of any other SVG element, by positioning the same location of text coordinate with another element. We can easily change the horizontal alignment of text by using text attribute called anchor-text to the middle as shown below.
Adding new line in SVG Text
In our first example, we had added 3 texts manually. In the HTML we write a paragraph and we can put a break or new line character into the paragraph. We can’t add a new line to text in D3, we can only achieve this with help of tspan in D3.
In above code, we are creating a text element with three tspan an element inside the text element inSVG. At the last a highlight line code, we are dynamically creating text with help of text array data.