line connect

by Cyril Cherian

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>
<svg id="main" width="500" height="500" style="background-color: white">
    <rect id="a" x="100" y="100" height="50" width="50" style="fill: blue"></rect>
    <rect id="b" x="400" y="400" height="50" width="50" style="fill: blue"></rect>
    <line id="c" x1="100" y1="100"  y2="400" x2="400" style="stroke:rgb(255,0,0);stroke-width:2;display:none"></line>
</svg>

CSS

body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: auto;
  position: relative;
  width: 960px;
}

text {
  font: 10px sans-serif;
}

form {
  position: absolute;
  right: 10px;
  top: 10px;
}

JavaScript

d3.select("#a").on('mousedown', function(d){
     d3.select("#c").style("display","");//make the line visible when mouse click is down.
});
d3.select("#b").on('mouseup', function(d){
     d3.select('#c')
        .attr('x2', 400)
        .attr('y2', 400);
//remove all the listeners as we have made the connection line    
    d3.select("#main").on('mousemove',null);
    d3.select("#a").on('mousedown',null);
    d3.select("#b").on('mouseup',null);
});
d3.select("#main").on('mousemove', function(d){
    //on mouse move update the line.
    var mouseLoc = d3.mouse(this);
    d3.select('#c')
        .attr('x2', mouseLoc[0]-5)
        .attr('y2', mouseLoc[1]-5);

});