【发布时间】:2015-06-14 13:15:51
【问题描述】:
我正在尝试在 d3js 中连接两个可拖动的矩形。我的要求是
- 有不同的矩形(例如 A、B、C)
- 所有矩形都应该是可拖动的
- 当我点击一个矩形时,它应该开始画一条线 (例如,如果我先单击 A,则该行应从 A.x、A.y 开始。行尾应随鼠标点移动)
- 当我单击第二个矩形时,该行应以该元素结束 (例如,如果我在 A 之后单击 B,现在应该连接 A 和 B)
到目前为止,我可以拖动矩形,如果它们是静态的,我可以连接它们。但是当我在加入矩形后移动矩形时,线应该随着矩形移动。
这是我工作的fiddle。有人可以在这里指导我吗?
<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>
function move() {
d3.select(this)
.attr('x', d3.event.x - parseInt(d3.select(this).attr("width")) / 2)
.attr('y', d3.event.y - parseInt(d3.select(this).attr("height")) / 2);
}
var drag = d3.behavior.drag().on('drag', move);
d3.select("#a").on('mousedown', function(d){
d3.select("#c").style("display","");//make the line visible when mouse click is down.
}) .call(drag);
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);
}) .call(drag);
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);
});
【问题讨论】:
标签: javascript svg d3.js