当节点太小时,我该如何在d3中隐藏文本标签?

5

我正在创建一个可缩放的太阳图,类似于这个示例。问题是我的太阳图中有很多数据,因此文本标签会挤在一起,难以阅读。因此,当它们太小时,我想隐藏标签,就像这个d3.partition.layout示例中一样。如何实现这个功能?

2个回答

2

我刚刚通过添加以下内容使其工作:

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); });
        }
    });
}

0
一般来说,要实现这个功能,您需要绘制文本元素,使用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} 。= / - Elfayer
你设置好内容了吗?你可能想要提出一个关于这个的单独问题。 - Lars Kotthoff
如何计算盒子的可用空间? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接