Search code examples
javascriptsvgd3.js

D3 - Create Dynamic "Border" Rectangle around SVG group


I have an SVG group with a rect inside of it, and would like the rect to act as a border for the group...

<g>
  <rect></rect>
</g>

but the group is dynamic and its content changes. I am attempting to resize the rect in my update function as such

.attr("x", function(d) { return this.parentNode.getBBox().x })
.attr("y", function(d) { return this.parentNode.getBBox().y })
.attr("width", function(d) { return this.parentNode.getBBox().width })
.attr("height", function(d) { return this.parentNode.getBBox().height })

But what seems to happen is that it expands relatively fine, but then cannot shrink properly since the group's bounding box width is now the same as the expanded rect's width (the rect's width is the group's width, but the group's width is now the rect's width).

Is there any way to get a rectangle inside an SVG group to properly resize and act as a border?


Solution

  • The simplest, cross-browser compatible way is to implement a border is to use a rect exactly as I did, but place it outside of the group, as mentioned by @Duopixel in his comment. As it is still positioned by the bounding box, it will have the correct width, height, x, and y.

    <rect></rect>
    <g></g>