Javascript 连接d3js中的两个矩形
我试图用d3中的一条线连接两个矩形。行为应该是这样的, 假设我们有矩形A和B。我们必须首先单击一个矩形,当我们移动鼠标时,线必须随着鼠标移动,当我单击B时。线应该连接A和B 这就是我现在拥有的。我无法更新线路。它不断添加新线对象Javascript 连接d3js中的两个矩形,javascript,svg,d3.js,Javascript,Svg,D3.js,我试图用d3中的一条线连接两个矩形。行为应该是这样的, 假设我们有矩形A和B。我们必须首先单击一个矩形,当我们移动鼠标时,线必须随着鼠标移动,当我单击B时。线应该连接A和B 这就是我现在拥有的。我无法更新线路。它不断添加新线对象 <svg id="main" width="500" height="500" style="background-color: red"> <rect id="a" x="100" y="100" height="50" width="50
<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>
d3.选择(“a”)
.on('点击')功能(d){
var elem=d3。选择(此项);
var mouseLoc=d3.mouse(this);
d3.选择(“#主”)
.on('mousemove',函数(d){
//d3.选择('#li')。删除();
d3.选择(“#main”)。追加(“行”)
.attr('id','li')
.attr('x1',elem.attr('x'))
.attr('y1',elem.attr('y'))
.attr('x2',d3.鼠标(此)[0]+5)
.attr('y2',d3.鼠标(此)[1]+5)
.attr(“笔划”,函数(d){返回“黑色”;})
.style(“笔划宽度”,函数(d){返回“1px”;});
})
;
console.log('clicked');
});
代码中的问题是在鼠标移动时添加了新行,但您应该刚刚更新了该行
我已经写了一个小提琴的要求,你也张贴了意见,为您的帮助
d3.在('mousedown',函数(d)上选择('a'){
d3.选择(“#c”).style(“display”,”“);//当鼠标点击时,使线条可见。
});
d3.在('mouseup',函数(d)上选择('b'){
d3.选择(“#c”)
.attr('x2',400)
.attr('y2',400);
//删除所有侦听器,因为我们已经建立了连接线
d3.在('mousemove',null)上选择('main');
d3.选择('mousedown',空);
d3.在('mouseup',null)上选择('b');
});
d3.选择('mousemove',函数(d)上的('main'){
//在鼠标移动时更新该行。
var mouseLoc=d3.mouse(this);
d3.选择(“#c”)
.attr('x2',鼠标[0]-5)
.attr('y2',mouseLoc[1]-5);
});代码>
谢谢+1.征求意见。