translate values when zoomed

Hi! I am new to Observable but I been working with D3 in my last project.

I have a Network Graph that I would like to center to the new branch every time I add a new one. For doing so, I am calculating the translate x and y like this:

var dcx = (window.innerWidth/2-networkGraph.coorX)/networkGraph.zoomScale;
var dcy = (window.innerHeight/2-networkGraph.coorY)/networkGraph.zoomScale;
networkGraph.g.transition()
      .duration(750).attr("transform",  "translate("+ dcx + "," + dcy  + ") scale("+networkGraph.zoomScale+")") 

It is working fine if the graph is not zoomed out but it is not centering the graph to the new nodes if it is zoomed out.

I have tried many things but nothing works. Could anybody help me with that?

Thanks!

Teresa

Hi, and welcome to Observable!

I believe you’re missing a second translate:

networkGraph.g.transition()
  .duration(750)
  .attr(
    "transform",
    `translate(${dcx},${dcy}) scale(${networkGraph.zoomScale}) translate(${-dcx},${-dcy})`
  ) 

If you’re still having problems, can you please share a link to your notebook?

1 Like