0

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.

Christopher Chiche
  • 15,075
  • 9
  • 59
  • 98
  • 1
    Maybe similar to your question? http://stackoverflow.com/questions/4991171/auto-line-wrapping-in-svg-text – Wex Dec 10 '12 at 18:51

2 Answers2

1

If you want automatic line wrapping, foreignObject with a div is the way to go. The problems you mention can be fixed relatively easily. While you're setting myCSS for the svg element, you're not setting it for the div. If you add the line to set the CSS class after appending the div, 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 the div.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
1

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:

<p><span></span><span>This is some text which will wrap if it gets too long!</span></p>​

CSS:

* { margin: 0; padding: 0; }
body { font: 10px sans-serif; }
p { 
    background: red;
    text-align: center;
    border-radius: 50px; 
    width: 100px; 
    height: 100px; }
p span { 
    vertical-align: middle;
    display: inline-block; }
p span:first-child { height: 100px; }

This also has the advantage of being supported on IE7 and IE8.

Wex
  • 15,539
  • 10
  • 64
  • 107