How to Include Multiple SVG Elements in a D3.js forceSimulation Node

Explains how to include multiple SVG elements in a node in D3.js and drag elements such as text together.

Example program

This is a D3.js forceSimulation demo that groups multiple SVG elements into one draggable node.

View code

Example code

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>D3 v7 force simulation group element</title>
</head>

<body>
  <svg width="800" height="600"></svg>
  <script src="https://d3js.org/d3.v7.min.js"></script>
  <script>
    // 1. Prepare the data to draw
    var width = document.querySelector("svg").clientWidth;
    var height = document.querySelector("svg").clientHeight;
    var nodesData = [];
    for (var i = 0; i < 50; i++) {
      nodesData.push({
        "x": width * Math.random(),
        "y": height * Math.random(),
        "r": 40 * Math.random() + 5
      });
    }

    // 2. Add SVG elements
    var nodeGroup = d3.select("svg")
      .selectAll("g")
      .data(nodesData)
      .enter()
      .append("g")
      .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

    nodeGroup.append("circle")
      .attr("cx", function (d) { return d.x; })
      .attr("cy", function (d) { return d.y; })
      .attr("r", function (d) { return d.r })
      .attr("fill", "Gold")
      .attr("stroke", "black")
      .append("title")
      .text("This is title.");

    nodeGroup.append("text")
      .attr("x", function (d) { return d.x; })
      .attr("y", function (d) { return d.y; })
      .attr("text-anchor", "middle")
      .attr("dominant-baseline", "middle")
      .style("fill", "steelblue")
      .text("Ball")
      .append("title")
      .text("This is title.");

    // 3. Configure forceSimulation
    var simulation = d3.forceSimulation()
      .force("collide",
        d3.forceCollide()
          .radius(function (d) { return d.r + 1 }))
      .force("charge", d3.forceManyBody())
      .force("x", d3.forceX().strength(0.05).x(width / 2))
      .force("y", d3.forceY().strength(0.05).y(height / 2));

    simulation
      .nodes(nodesData)
      .on("tick", ticked);

    // 4. forceSimulation drawing update function
    function ticked() {
      nodeGroup.select("circle")
        .attr("cx", function (d) { return d.x; })
        .attr("cy", function (d) { return d.y; });
      nodeGroup.select("text")
        .attr("x", function (d) { return d.x; })
        .attr("y", function (d) { return d.y; });
    }

    // 5. Drag event functions
    function dragstarted(event, d) {
      if (!event.active) simulation.alphaTarget(0.3).restart();
      d.fx = d.x;
      d.fy = d.y;
    }

    function dragged(event, d) {
      d.fx = event.x;
      d.fy = event.y;
    }

    function dragended(event, d) {
      if (!event.active) simulation.alphaTarget(0);
      d.fx = null;
      d.fy = null;
    }
  </script>
</body>

</html>

Explanation

This example program uses forceSimulation. For details about forceSimulation, see this page.

Only part of the program is explained here.

  var nodeGroup = d3.select("svg")
    .selectAll("g")
    .data(nodesData)
    .enter()
    .append("g")
    .call(d3.drag()
      .on("start", dragstarted)
      .on("drag", dragged)
      .on("end", dragended));

First, create a <g> element that represents a group element. Assign the node data array to the <g> element and register the drag events.

Next, add <circle> and <text> as child elements of the <g> tag. Since the node data array is assigned to the <g> element, the child elements can use that data. You can also set title as a child element of <circle> and <text>. In the example program, the title string appears when the cursor is placed over a node, although it does not appear on tablets or smartphones.

  nodeGroup.append("circle")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", function(d) { return d.r })
    .attr("fill", "Gold")
    .attr("stroke", "black")
    .append("title")
    .text("This is title.");

  nodeGroup.append("text")
    .attr("x", function(d) { return d.x; })
    .attr("y", function(d) { return d.y; })
    .attr("text-anchor", "middle")
    .attr("dominant-baseline", "middle")
    .style("fill", "steelblue")
    .text("Ball")
    .append("title")
    .text("This is title.");

If you do not use forceSimulation and want movement only through drag, change the event function as follows.

function dragged(event, d) {
  d3.select(this).select("circle")
    .attr("cx", d.x = event.x)
    .attr("cy", d.y = event.y);
  d3.select(this).select("text")
    .attr("x", d.x = event.x)
    .attr("y", d.y = event.y);
}