D3 Adding Text to an SVG Rectangle

I want to add html to a rectangle in D3 to give me a tooltip with multiple lines. The bottom is how I add the rectangle, which may be part of the problem. The top is the code that should work in my world.

newRect.().html(" <textArea font-family=Verdana font-size=20 fill=blue > Test " + "</br>" + "Test2 </textArea>"); 

What inserts a text field into SVG, it just doesn't appear:
HTML

 <rect id="rectLabel" x="490" y="674" width="130" height="160" fill="red"> <textarea fill="blue" font-size="20" font-family="Verdana"> Test </br>Test2 </textarea> </rect> 

I have a mouse function that runs the following:

  newRect = svg.append("rect") .attr("x", xCor) .attr("y", yCor) .attr("width", 130) .attr("height", 160) .attr("fill", "red") .attr("id", "rectLabel"); 

I think I should do it, but it won’t work. It just removes the g.node I'm trying to add to.

  newRect = $(this).enter().append("rect") .attr("x", xCor) .attr("y", yCor) .attr("width", 130) .attr("height", 160) .attr("fill", "red") .attr("id", "rectLabel"); 

Question: Why is my text not appearing? Ive tried .html, .textArea. I want a multi-line shortcut, so I don't think .text will work correctly? Also, how should I add a rectangle?

+44
javascript svg
Dec 17 '13 at 20:51
source share
2 answers

A rect cannot contain a text element. Instead, transform the g element with the location of the text and the rectangle, then add both the rectangle and the text to it:

 var bar = chart.selectAll("g") .data(data) .enter().append("g") .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; }); bar.append("rect") .attr("width", x) .attr("height", barHeight - 1); bar.append("text") .attr("x", function(d) { return x(d) - 3; }) .attr("y", barHeight / 2) .attr("dy", ".35em") .text(function(d) { return d; }); 

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a bit complicated, you can check this wrapper function .

+90
Dec 17 '13 at 21:06
source share

Have you tried the SVG text element?

 .append("text").text(function(d, i) { return d[whichevernode];}) 

The rect element does not allow the use of a text element inside it. It allows only descriptive elements ( <desc>, <metadata>, <title> ) and animation elements ( <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set> )

Add a text element as a sibling and work with positioning.

UPDATE

Using g grouping, how about something like that? violin

Of course, you can move the logic to a CSS class to which you can add, remove from the group (this.parentNode)

+7
Dec 17 '13 at 21:02
source share



All Articles