javascript - Connecting two rectangles in d3js -
i trying connect 2 rectangles line in d3. behaviour should this,
let's have rectangles & b. have first click rectangle , when move mouse line has move mouse, when click b. line should connect & b.
this have now. can't update line. keeps adding new line objects.
<svg id="main" width="500" height="500" style="background-color: red"> <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> </svg> <script> d3.select("#a") .on('click', function(d){ var elem = d3.select(this); var mouseloc = d3.mouse(this); d3.select("#main") .on('mousemove', function(d){ // d3.select('#li').remove(); d3.select('#main').append("line") .attr('id', 'li') .attr('x1', elem.attr('x')) .attr('y1', elem.attr('y')) .attr('x2', d3.mouse(this)[0]+5) .attr('y2', d3.mouse(this)[1]+5) .attr("stroke", function (d) { return "black"; }) .style("stroke-width", function(d) { return "1 px"; }); }) ; console.log('clicked'); }); </script>
the problem in code appending new lines on mouse move, should have updated line.
i have written fiddle requirement have posted added comments help.
http://jsfiddle.net/cyril123/fy4cv1ab/6/
d3.select("#a").on('mousedown', function(d){ d3.select("#c").style("display","");//make line visible when mouse click down. }); d3.select("#b").on('mouseup', function(d){ d3.select('#c') .attr('x2', 400) .attr('y2', 400); //remove listeners have made 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 line. var mouseloc = d3.mouse(this); d3.select('#c') .attr('x2', mouseloc[0]-5) .attr('y2', mouseloc[1]-5); });
<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>
Comments
Post a Comment