score:3

Accepted answer

If I'm understanding you correctly, it would be simpler to append the rectangle, append the text, then size the rectangle to the text:

<!DOCTYPE html>
<html>

  <head>
    <script src="https://d3js.org/d3.v5.min.js"></script>
  </head>

  <body>
    <svg width="900" height="900"></svg>
    <script>
      
      var svg = d3.select('svg');
      
      var rect = svg.append("rect")
        .style("fill", "black")
        .attr("x", 20)
        .attr("y", 20);
      
      var text = svg.append("text")
        .text("Now is the time for all good men to come to the aid of their country")
        .attr("x", 20)
        .attr("y", 20)
        .attr("alignment-baseline","hanging")
        .style("fill","steelblue")
        .style("font-family", "arial")
        .style("font-size", "14pt")
        
      var bbox = text.node().getBBox();
      
      rect.attr("width", bbox.width);
      rect.attr("height", bbox.height);
    </script>
  </body>

</html>


Related Query