我使用d3绘制带有单选按钮的饼来更改显示的路径。我的问题是根据新路径重新计算标签位置。在加载时,标签被正确绘制,但在点击时仍然与第一次加载相同。 我认为问题在于g只占用了第一个数据值,而且我不知道怎么说取当前数据值。
绘制标签的功能是
//Labels
d3.selectAll("g").select("text").transition()
.ease("linear")
.duration(500)
.style("opacity", 0).remove();
svg.selectAll("g").append("text")
.attr("transform", function (d) {
var c = arc.centroid(d),
x = c[0],
y = c[1],
// pythagorean theorem for hypotenuse
h = Math.sqrt(x * x + y * y);
return "translate(" + (x / h * labelr) + ',' +
(y / h * labelr) + ")";
})
.attr("dy", ".35em")
.style("opacity", 0)
.style("fill", "#000")
.style("font-size", 12)
.attr("text-anchor", function (d) {
// are we past the center?
return (d.endAngle + d.startAngle) / 2 > Math.PI ?
"end" : "start";
})
.text(function (d) { return d.data.label; })
.transition()
.ease("linear")
.delay(1000)
.duration(500)
.style("opacity", 1);
有关详细信息,请参阅https://jsfiddle.net/w0ckw4tb/
由于
答案 0 :(得分:2)
在添加新文本节点之前,只需应用新数据绑定:
svg.selectAll("g").data(pie) // <== !!!
.append("text")
.attr("transform" ...
如果你没有这样做,这段代码:
.attr("transform", function (d) {
var c = arc.centroid(d),
x = c[0],
y = c[1],
// pythagorean theorem for hypotenuse
h = Math.sqrt(x * x + y * y);
return "translate(" + (x / h * labelr) + ',' +
(y / h * labelr) + ")";
})
返回transform
属性的相同值,因此标签保留在同一位置。