简体   繁体   中英

d3 force graph with divs and d3 zoom

Hello Stackoverflowcommunity! I am having trouble getting d3 zoom working in my d3force-directed graph. I could achieve that it is zooming and panning but doing so breaks the alignment between the nodes and the links and i don't know how i could fix it.... I created a fiddle showing what i mean. https://jsfiddle.net/5jgrf5h8/5/

This is the code where i perform the zoom:

svg.call(d3.zoom()
  //.scaleExtent([1 / 2, 4])
  .on("zoom", zoomed))
.on("dblclick.zoom", null);
//.on("wheel.zoom", null);

function zoomed() {
  //link.attr("transform", d3.event.transform);
  link.attr("transform", "translate(" + d3.event.transform.x + "," + d3.event.transform.y + ") scale(" + d3.event.transform.k + ")");
  node.style("transform", "translate(" + d3.event.transform.x + "px," + d3.event.transform.y + "px) scale(" + d3.event.transform.k + ")");

  simulation.alphaTarget(0.001).restart();
  simulation.alphaTarget(0);
}

When you apply the CSS scale on your div nodes, it's with an origin of 0,0 not with an origin of the position they are current in.

Try this:

function zoomed() {

    // apply CSS scale with respect to current position
    node.each(function(d){
    var self = d3.select(this),
            x = self.style("left"),
        y = self.style("top");
    self.style("transform-origin", "-" + x + " -" + y);
  })

  link.attr("transform", "translate(" + d3.event.transform.x + "," + d3.event.transform.y + ") scale(" + d3.event.transform.k + ")");
  node.style("transform", "translate(" + d3.event.transform.x + "px," + d3.event.transform.y + "px) scale(" + d3.event.transform.k + ")");

  simulation.alphaTarget(0.001).restart();
  simulation.alphaTarget(0);
}

Updated fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM