我正在努力用D3实现节点折叠功能。我得到了一个可以折叠和扩展节点的点,但转换并不平滑,并且折叠节点的父节点被销毁。
constructor(private element: ElementRef) {
this.htmlElement = this.element.nativeElement;
this.host = D3.select(this.element.nativeElement);
}
draw(issue) {
if (!issue) {
return;
}
var zoom = D3.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var nodes = D3.hierarchy(issue, function (d) {
return d.children;
});
nodes = this.treemap(nodes);
while (this.htmlElement.hasChildNodes()) {
this.htmlElement.removeChild(this.htmlElement.lastChild);
}
var svg = this.host.append('svg')
.attr("width", this.width + this.margin.left + this.margin.right)
.attr("height", this.height + this.margin.top + this.margin.bottom);
var g = svg.append("g")
.attr("transform",
"translate(" + this.margin.left + "," + this.margin.top + ")");
svg.call(zoom);
var link = g.selectAll(".link")
.data(nodes.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("d", function (d) {
return "M" + d.y + "," + d.x
+ "C" + (d.y + d.parent.y) / 2 + "," + d.x
+ " " + (d.y + d.parent.y) / 2 + "," + d.parent.x
+ " " + d.parent.y + "," + d.parent.x;
});
var node = g.selectAll(".node")
.data(nodes.descendants())
.enter().append("g")
.attr("class", function (d) {
return "node" +
(d.children ? " node--internal" : " node--leaf");
})
.attr("transform", function (d) {
return "translate(" + d.y + "," + d.x + ")";
})
.on('click', (function (d) {
if (d.data.children) {
d.data._children = d.data.children;
d.data.children = null;
} else {
d.data.children = d.data._children;
d.data._children = null;
}
this.draw(d.data);
}).bind(this));
node.append("circle")
.attr("r", 10);
node.transition()
.duration(750)
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});
node.select('circle.node')
.attr('r', 10)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
})
.attr('cursor', 'pointer');
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(750)
.attr("transform", function (d) { return "translate(" + issue.y + "," + issue.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// adds the text to the node
node.append("text")
.attr("dy", ".35em")
.attr("x", function (d) { return d.children ? -13 : 13; })
.style("text-anchor", function (d) {
return d.children ? "end" : "start";
})
.text(function (d) { return d.data.name; });
function zoomed() {
g.attr("transform", D3.event.transform);
}
}
感谢一些帮助让它工作:) 我试图根据这篇文章实施:https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5ecd
编辑I:我还在此处添加了代码https://stackblitz.com/edit/angular-f3suie