【问题标题】:How do I hide the text labels in d3 when the nodes are too small?当节点太小时,如何隐藏 d3 中的文本标签?
【发布时间】:2013-09-20 09:44:56
【问题描述】:

我正在创建一个类似于 example 的可缩放旭日形。问题是我的 sunburst 中有很多数据,所以文本标签混合在一起,难以阅读。因此,我想在标签太小时隐藏标签,就像在这个d3.partition.layout 示例中一样。我该如何实现这个功能?

【问题讨论】:

    标签: javascript d3.js labels sunburst-diagram


    【解决方案1】:

    我刚刚通过添加以下内容来完成这项工作:

    var kx = width / root.dx, ky = height / 1;
    

    然后在文本声明部分执行以下操作:

    var text = g.append("text")
      .attr("transform", function(d) { return "rotate(" + computeTextRotation(d) + ")"; })
      .attr("x", function(d) { return y(d.y); })
      .attr("dx", "6") // margin
      .attr("dy", ".35em") // vertical-align
      .attr("opacity", function(d) { return d.dx * ky > 10 ? 1 : 0; })
      .text(function(d) { return d.name; });
    

    上面的关键部分是这一行:

    .attr("opacity", function(d) { return d.dx * ky > 10 ? 1 : 0; })
    

    如果不够大,这会将不透明度设置为 0。然后在点击函数中你需要做同样的事情,如下:

    function click(d) {
      // fade out all text elements
      text.transition().attr("opacity", 0);
    
      kx = (d.y ? width - 40 : width) / (1 - d.y);
      ky = height / d.dx;
    
      path.transition()
        .duration(750)
        .attrTween("d", arcTween(d))
        .each("end", function(e, i) {
        // check if the animated element's data e lies within the visible angle span given in d
        if (e.x >= d.x && e.x < (d.x + d.dx)) {
          // get a selection of the associated text element
          var arcText = d3.select(this.parentNode).select("text");
          // fade in the text element and recalculate positions
          arcText.transition().duration(750)
            .attr("opacity", 1)
            .text(function(d) { return d.name; })
            .attr("opacity", function(d) { return e.dx * ky > 10 ? 1 : 0; })
            .attr("transform", function() { return "rotate(" + computeTextRotation(e) + ")" })
            .attr("x", function(d) { return y(d.y); });
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      一般来说,要实现这一点,您需要绘制文本元素,使用getBBox() 获取其实际大小,并根据该大小,显示或不显示。代码看起来像这样。

       svg.append("text")
          .style("opacity", function() {
            var box = this.getBBox();
            if(box.width <= available.width && box.height <= available.height) {
              return 1; // fits, show the text
            } else {
              return 0; // does not fit, make transparent
            }
          });
      

      当然,您也可以完全删除 text 元素,但这需要单独通过。

      【讨论】:

      • 就我而言,this.getBBox(); 总是返回 SVGRect {height: 0, width: 0, y: 0, x: 0} 。 =/
      • 你设置内容了吗?您可能想就此提出一个单独的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 2019-01-15
      • 2023-04-02
      • 2013-02-18
      相关资源
      最近更新 更多