我正在使用平移和缩放功能实现 d3 树版本 4。为了使节点与版本 3 居中,我从版本 3 示例中找到了以下内容。
// Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children.
function centerNode(source) {
scale = zoomListener.scale();
x = -source.y0;
y = -source.x0;
x = x * scale + viewerWidth / 2;
y = y * scale + viewerHeight / 2;
d3.select('g').transition()
.duration(duration)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")");
zoomListener.scale(scale);
zoomListener.translate([x, y]);
}
我在版本 4 中有以下内容
_treeChanged: function() {
console.log(this.localName + '#' + this.id + ' tree data has changed');
// Assigns parent, children, height, depth
var aa = this.$.polymerTree.getBoundingClientRect();
var svg_height = aa.height - 20 - 30;
var svg_width = aa.width - 90 - 90;
this.root = d3.hierarchy(this.tree, function(d) { return d.children; });
this.root.x0 = svg_height / 2;
this.root.y0 = 0;
if (g) {
g.remove();
}
zoomListener = d3.zoom()
.scaleExtent([.5, 10])
.on("zoom", function () {
g.attr("transform", d3.event.transform);
}
);
g = d3.select(this.$.polymerTree)
.call(zoomListener)
.on("dblclick.zoom", null)
.append("g");
if (this.treemap) {
this.update(this.root);
this.centerNode(this.root);
}
},
我应该如何实现中心节点才能使用版本 4?
我的工作 d3 树位于 https://github.com/powerxhub/emh-d3-tree
谢谢!
最佳答案
我找到了自己的修复方法:
centerNode: function(source) {
var aa = d3Polymer.$.polymerTree.getBoundingClientRect();
var svg_height = aa.height - 20 - 30;
var svg_width = aa.width - 90 - 90;
t = d3.zoomTransform(d3Polymer.$.polymerTree);
/*
To keep the node to be centered at the same x coordinate use
x = t.x;
To position the node at a certain x coordinate, use
x = source.y0;
x = -x *t.k + 50;
*/
x = t.x;
y = source.x0;
y = -y *t.k + svg_height / 2;
g.transition()
.duration(750)
.attr("transform", "translate(" + x + "," + y + ")scale(" + t.k + ")")
.on("end", function(){ g.call(zoomListener.transform, d3.zoomIdentity.translate(x,y).scale(t.k))});
},
我在 d3.js rewriting zoom example in version4 的相关帖子中得到了它。 .
您可以通过在添加了缩放的元素上调用 ZoomTransform 来获取 t。就我而言,它直接位于 SVG 上。 g 是具有边界 SVG g 组件的元素。这是设置缩放的代码:
zoomListener = d3.zoom()
.scaleExtent([.5, 10])
.on("zoom", function () {
g.attr("transform", d3.event.transform);
}
);
g = d3.select(this.$.polymerTree)
.call(zoomListener)
.on("dblclick.zoom", null)
.append("g");
其中 this.$.polymerTree 是 SVG 元素。
关于javascript - 如何在 D3.js 版本 4 中执行节点居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41450199/