D3.js Auto font-sizing based on nodes individual radius/diameter

后端 未结 3 527
猫巷女王i
猫巷女王i 2020-12-16 00:24

How can I have D3.js automatically adjust font-size for each node based on their individual radius/diameter?

I use a style that allows automatic inc

3条回答
  •  悲&欢浪女
    2020-12-16 01:19

    Alternatively, you can create text label embedded with each node as follows:

    this.g.append("g")
      .attr("class", "labels")
      .selectAll(".mytext")
      .data(NODE_DATA)
      .enter()
      .append("text")
      .text(function (d) {
         return d.LabelText; // Here label text is the text that you want to show in the node
      })
      .style("font-size", "1px")
      .attr("dy", ".35em") // You can adjust it
      .each(function (d) {
          var r = Number(d.Size), a = this.getComputedTextLength(),
              c=0.35, // Same as dy attribute value
              b = 2*Math.sqrt(r*r-c*c), s = Math.min(r, b/a);
          d.fs = s;
      })
      .style("font-size", function (d) {
         return d.fs + "px";
      })
    

提交回复
热议问题