Acy
Acy

Reputation: 659

How to properly use the Use tag in SVG with d3 js?

I know that d3 renders elements based on the called order. So if I want to render white text over a black rectangle, I can just call the rect first and then call the white text.

However, in my particular case, my rect's dimension is based on the my white text, so I have to call the white text first.

A go-around I found was to use the use tag, but I couldn't get it to work, here's my current attempt:

the text:

      var textToolTip = gToolTip
        .append("text")

        .attr("id", "toUse")
        .text(.....)...

the use tag:

var useText = gToolTip.append("use").attr("xlink:xlink:href", "#toUse");

I have also tried to give textToolTip xlink:href but it didn't work. For use tag, I have tried to use xlink:href instead of xlink:xlink:href, it didn't work. I am using double xlink because of this answer I found: How do I define an SVG doc under <defs>, and reuse with the <use> tag?

Upvotes: 2

Views: 810

Answers (1)

Mark
Mark

Reputation: 108522

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>

Upvotes: 3

Related Questions