我正在创建与此示例类似的可缩放旭日形。问题是我的 sunburst 中有很多数据,所以文本标签混合在一起,难以阅读。因此,我想在标签太小时隐藏标签,就像在这个d3.partition.layout示例中一样。我该如何实现这个功能?
问问题
4583 次
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。然后在 click 函数中你需要做同样的事情,如下所示:
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); });
}
});
}
于 2017-02-28T14:51:13.100 回答
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
元素,但这需要单独通过。
于 2013-09-16T10:21:09.723 回答