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

标签 javascript d3.js label sunburst-diagram

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

最佳答案

我刚刚通过添加以下内容使它正常工作:

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

关于javascript - 当节点太小时,如何在 d3 中隐藏文本标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18824684/

相关文章:

Javascript 在 FF 和 IE 中工作..但 Chrome 说 "cannot call method of null"!

javascript - 为什么即使prototype被覆盖, `obj instanceof ConstructorFunc`仍然返回true?

javascript - D3.js 中的悬停效果

javascript - 在 D3 中包装文本

更改应用程序名称和 Activity 标签时的 Android 奇怪行为

javascript - Vue.js + Webpack + vue-loader + bootstrap-sass + sass-loader

javascript - jQuery 选择框显示/隐藏 div

javascript - 在 Javascript 中提取大型多维数组的切片

firefox - 如何从网页打印到标签打印机

R:geom_vline 标签上的上标