I would like to be able to set the width of a text element in D3. For now I have some text in a circle but I cannot set the width of this element. (let's say that nodeEnter
is a node in my graph)
nodeEnter.append("circle")
.attr("r", function(d){return d.radius+"px";});
/* Add text in middle of circle */
nodeEnter.append('text')
.text("this is a very long text");
What I would like is to find a simple way of setting the width of that text element (with the overflow going down, as in a simple div
). The way I have right now is the following:
nodeEnter.append("circle")
.attr("r", function(d){return d.radius+"px";});
/* Add text in middle of circle */
nodeEnter.append("foreignObject")
.attr("width", 130)
.attr("height", 200)
.attr("class", "myCSS")
.append("xhtml:div")
.html("this is a very long text");
However I don't think that it is the best solution, for example everything I set in myCSS
is overwriten. Moreover I don't know how to center the foreign Object in the circle (especially on the x axis).
Thanks in advance for your help.
If you want automatic line wrapping,
foreignObject
with adiv
is the way to go. The problems you mention can be fixed relatively easily. While you're settingmyCSS
for the svg element, you're not setting it for thediv
. If you add the line to set the CSS class after appending thediv
, it should pick up the settings.The easiest way to center the text is probably to set the size of the
div
to touch the edges of the circle and add the CSS to center the text within thediv
.If you're just creating circles, you could always just use regular HTML elements to create the circles and absolute positioning to position them.
http://jsfiddle.net/FPkxV/
HTML:
CSS:
This also has the advantage of being supported on IE7 and IE8.