score:56

Accepted answer

i have made a small code snippet. hope this is helpful.

var data = {
   nodes: [{
     name: "a",
     x: 200,
     y: 150
   }, {
     name: "b",
     x: 140,
     y: 300
   }, {
     name: "c",
     x: 300,
     y: 300
   }, {
     name: "d",
     x: 300,
     y: 180
   }],
   links: [{
     source: 0,
     target: 1
   }, {
     source: 1,
     target: 2
   }, {
     source: 2,
     target: 3
   }, ]
 };

 var c10 = d3.scale.category10();
 var svg = d3.select("body")
   .append("svg")
   .attr("width", 1200)
   .attr("height", 800);

 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);
       }
     });
   });

 var links = svg.selectall("link")
   .data(data.links)
   .enter()
   .append("line")
   .attr("class", "link")
   .attr("x1", function(l) {
     var sourcenode = data.nodes.filter(function(d, i) {
       return i == l.source
     })[0];
     d3.select(this).attr("y1", sourcenode.y);
     return sourcenode.x
   })
   .attr("x2", function(l) {
     var targetnode = data.nodes.filter(function(d, i) {
       return i == l.target
     })[0];
     d3.select(this).attr("y2", targetnode.y);
     return targetnode.x
   })
   .attr("fill", "none")
   .attr("stroke", "white");

 var nodes = svg.selectall("node")
   .data(data.nodes)
   .enter()
   .append("circle")
   .attr("class", "node")
   .attr("cx", function(d) {
     return d.x
   })
   .attr("cy", function(d) {
     return d.y
   })
   .attr("r", 15)
   .attr("fill", function(d, i) {
     return c10(i);
   })
   .call(drag);
svg {
    background-color: grey;
}
<script src="https://d3js.org/d3.v3.min.js"></script>

score:5

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);
       }
     });
   });

Related Query