Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3js V4 Center Node in Zoomable Tree

Tags:

svg

d3.js

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) );
}
like image 549
Tokker Avatar asked Mar 02 '17 10:03

Tokker


1 Answers

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) );
}
like image 197
Mammo Avatar answered Sep 30 '22 12:09

Mammo