I've found this example from Rob Schmuecker for centering a node in a tree which was clicked. This example works with D3js version 3. I ported this example to d3js version 4. But in my example the svg will jump after centering if i try to move svg. Does anybody know whats going wrong? Here some code snippets.
var baseSvg = d3.select("#tree-container").append("svg").attr("width", viewerWidth)
.attr("height", viewerHeight)
.attr("class", "overlay")
.call(zoomListener);
function zoom() {
if(d3.event.transform != null) {
svgGroup.attr("transform", d3.event.transform );
}
}
function centerNode(source) {
t = d3.zoomTransform(baseSvg.node());
x = -source.y0;
y = -source.x0;
x = x * t.k + viewerWidth / 2;
y = y * t.k + viewerHeight / 2;
d3.select('g').transition().duration(duration).call( zoomListener.transform, d3.zoomIdentity.translate(x,y).scale(t.k) );
}
Changing the selection within the centerNode from 'g' to 'svg' seems to do the trick. This is likely because the zoom listener is called on the svg element.
For reference, the centerNode function would now look like this:
function centerNode(source) {
t = d3.zoomTransform(baseSvg.node());
x = -source.y0;
y = -source.x0;
x = x * t.k + viewerWidth / 2;
y = y * t.k + viewerHeight / 2;
d3.select('svg').transition().duration(duration).call( zoomListener.transform, d3.zoomIdentity.translate(x,y).scale(t.k) );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With