Bob Haslett
Bob Haslett

Reputation: 1101

Add text into an svg path using d3

I've had a look around and can't see what I'm doing wrong. I'm trying to add text into and SVG path that looks like this

<path id="pumpButton" fill="#8AB065" d="M76.2,377.1H26.5c-3.1,0-5.7-2.6-5.7-5.7v-28.3c0-3.1,2.6-5.7,5.7-5.7h49.7c3.1,0,5.7,2.6,5.7,5.7v28.3C81.9,374.5,79.3,377.1,76.2,377.1z"><g x="10" y="10"><foreignObject dy=".35em" x="10" y="10" style="fill: white;">Turn on</foreignObject></g></path>

I'm using the following code:

var button=d3.select("#pumpButton");
    var g=button.append("g")
    .attr('x',10)
    .attr('y',10)
    g.append("text")
    .attr("dy", ".35em")
    .style('fill', 'white')
    .attr("x",10)
    .attr("y",10)
    .text("Turn on")

But I can't see anything on the screen. When I inspect the element it appears to be there but I can't see it.

The element looks like this when inspected

<g x="10" y="10"><text dy=".35em" x="10" y="10" style="fill: white;">Turn on</text></g>

Upvotes: 0

Views: 1479

Answers (1)

Robert Longson
Robert Longson

Reputation: 123985

SVG is divided into container elements (such as <g>, <svg>) and graphics elements such as <path> and <text>.

Graphics elements can only be children of containers, i.e. you can't nest a graphics element in a graphics element.

Don't try to make the text a child of the path, make it a subsequent sibling instead.

Upvotes: 3

Related Questions