Zack
Zack

Reputation: 13972

How do I adjust the "depth" of graphics in d3?

I am writing an animation using d3, and I cannot seem to find a way to easily ensure that a graphic always appears "behind" other graphics.

Specifically, I am dealing with lines and circles (imagine a directed graph), and it sort of looks bad to have some of the lines on top of the circles, and others underneath. Is there a way to set the z/depth of certain graphics, in this case my lines, manually? I apologize if this seems google-able, but I attempted typing "graphic depth d3" and other variations and got nothing.

EDIT : Accepted answer works, a more detailed description of the problem can be found here.

Upvotes: 0

Views: 449

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

SVG doesn't have a z-index property or similar, the elements are drawn in the order in which they appear in the DOM -- elements higher up are drawn behind elements that have been added afterwards.

The easiest way to group elements into layers is to use g elements. So in your example, I would use two g groups, one for the lines and one for the circles. Add the g for the lines first and then all of the lines underneath it. If you then add the circles to the second g that you added afterwards, all circles will always be on top of all lines.

Upvotes: 2

Related Questions