Simple graph of nodes and links without using force layout

前端 未结 2 392
猫巷女王i
猫巷女王i 2021-01-31 09:22

How can I make a basic connected graph (two nodes and a link connecting them for example) that doesn\'t use a force() layout? I just want to be able to drag a node

2条回答
  •  野的像风
    2021-01-31 09:22

    Gilsha has a great answer, but note that newer versions of d3 no longer use the behavior module.

    Instead of this:

    var drag = d3.behavior.drag()
       .on("drag", function(d, i) {
         d.x += d3.event.dx
         d.y += d3.event.dy
         d3.select(this).attr("cx", d.x).attr("cy", d.y);
         links.each(function(l, li) {
           if (l.source == i) {
             d3.select(this).attr("x1", d.x).attr("y1", d.y);
           } else if (l.target == i) {
             d3.select(this).attr("x2", d.x).attr("y2", d.y);
           }
         });
       });
    

    Simply change d3.behavior.drag() to d3.drag()

    var drag = d3.drag()
       .on("drag", function(d, i) {
         d.x += d3.event.dx
         d.y += d3.event.dy
         d3.select(this).attr("cx", d.x).attr("cy", d.y);
         links.each(function(l, li) {
           if (l.source == i) {
             d3.select(this).attr("x1", d.x).attr("y1", d.y);
           } else if (l.target == i) {
             d3.select(this).attr("x2", d.x).attr("y2", d.y);
           }
         });
       });
    

提交回复
热议问题