PurplePanda
PurplePanda

Reputation: 673

How to append multiple items to a force simulation node?

I'm using D3 v4 and can't seem to get multiple items to append to a node. In the code below I'm trying to get text to appear with the image as part of my force simulation. Both the image and text need to move together around the screen. It works perfectly if I only append either the image or the text but I can't get it to group both. When I run this it just shows 1 node in the corner.

this.node = this.d3Graph.append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(Nodes)
    .enter()
    .append("svg:image")
    .attr("xlink:href", 'https://seeklogo.com/images/T/twitter-2012-negative-logo-5C6C1F1521-seeklogo.com.png')
    .attr("height", 50)
    .attr("width", 50)
    .append("text")
    .attr("x", 20)
    .attr("y", 20)
    .attr("fill", "black")
    .text("test text");

this.force.on('tick', this.tickActions);

tickActions() {
    this.node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        })

    this.force
        .restart()
}

Upvotes: 3

Views: 154

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

You cannot append a <text> element to an <image> element. You have to append the <text> to the <g>.

The easiest solution is breaking your selection:

this.node = this.d3Graph.selectAll(null)
    .data(Nodes)
    .enter()
    .append("g")
    .attr("class", "nodes");

this.node.append("svg:image")
    .attr("xlink:href", 'https://seeklogo.com/images/T/twitter-2012-negative-logo-5C6C1F1521-seeklogo.com.png')
    .attr("height", 50)
    .attr("width", 50);

this.node.append("text")
    .attr("x", 20)
    .attr("y", 20)
    .attr("fill", "black")
    .text("test text");

Here we use the data to create <g> elements in the enter selection. Then, to each <g> element, we append an <image> and a <text> as children.

Upvotes: 2

Related Questions