DEV Community

loading...
Cover image for D3 Building Blocks #4: SVG Groups

D3 Building Blocks #4: SVG Groups

jessesbyers profile image Jesse Smith Byers ・2 min read

Now that we can draw individual elements on the SVG, we can start to group them and apply attributes and styling to the entire group at once.

Groups

Imagine you are creating a document that has multiple drawings, with text associated with each drawing. As you start to format attributes and move items around, it would be helpful to group each drawing with its associated text, and apply styling to the collection all at once. This is what groups allow us to in our SVGs. They act a as a container that holds other SVG elements together.

Setting Up A Group to Apply Common Attributes

To create a group, simply use a <g> tag to enclose all of the elements that you would like to group together. Then, assign attributes to the group, rather than to the individual elements.

Example 1: Groups in HTML

<svg>
    <g fill="red" stroke="orange" stroke-width="3px">
      <circle cx="20" cy="30" r="15"></circle>
      <rect x="10" y="70" width="20" height="20"></rect>
    </g>

    <g fill="blue" stroke="green" stroke-width="5px">
      <circle cx="80" cy="30" r="15"></circle>
      <rect x="70" y="70" width="20" height="20"></rect>
    </g>
  </svg>
Enter fullscreen mode Exit fullscreen mode

In the example above, we have set up two groups, which each include a circle and a rectangle element. Within each group, the circle and the rectangle have the same styling, since we applied the styling to the group rather than to the individual elements.

Example 2: Groups in D3

d3.select("svg")
  .append("g")
  .attr("id", "red");

d3.select("g#red")
  .append("circle")
  .attr("cx", 20)
  .attr("cy", 30)
  .attr("r", 15);

d3.select("g#red")
  .append("rect")
  .attr("x", 10)
  .attr("y", 70)
  .attr("width", 20)
  .attr("height", 20);

d3.select("g#red")
  .attr("fill", "red")
  .attr("stroke", "orange")
  .attr("stroke-width", "3px");


d3.select("svg")
  .append("g")
  .attr("id", "blue");

d3.select("g#blue")
  .append("circle")
  .attr("cx", 80)
  .attr("cy", 30)
  .attr("r", 15);

d3.select("g#blue")
  .append("rect")
  .attr("x", 70)
  .attr("y", 70)
  .attr("width", 20)
  .attr("height", 20);

d3.select("g#blue")
  .attr("fill", "blue")
  .attr("stroke", "green")
  .attr("stroke-width", "5px");
Enter fullscreen mode Exit fullscreen mode

In the example above, we have created the same drawing including two groups, a red group and a blue group. Note how we can assign each group a different id in order to style each group individually. In this example, we have applied styling using the D3 attribute method, but this styling could also be applied using CSS.

Read the SVG documentation to learn more about the Scalable Vector Graphics group element.

Discussion

pic
Editor guide