在d3js中移动连接的矩形

时间:2015-06-14 03:49:49

标签: javascript svg d3.js

我正在尝试在d3js中连接两个可拖动的矩形。我的要求是

  1. 有不同的矩形(例如A,B,C)
  2. 所有矩形都应该是可拖动的
  3. 当我点击一个矩形时,它应该开始画一条线 (例如,如果我先点击A,那么该行应该从A.x开始,A.y。行尾应该用鼠标点移动)
  4. 当我穿上第二个矩形时,该行应以该元素结束 (例如,如果我在A之后点击B,A& B应该立即连接)
  5. 到目前为止,我可以拖动矩形,如果它们是静态的,我可以连接它们。但是当我在接合它们之后移动矩形时,该线应随矩形移动。

    以下是我工作的fiddle。谁能指导我在这里?

    var seasons = new object[original.Length];
    for (int i = 0; i < original.Length; i++)
    {
           seasons[i] = original[i];
    }
    

1 个答案:

答案 0 :(得分:3)

您需要相应地更新具有属性的行。

以下是一个示例:http://jsfiddle.net/cyril123/kbj4xsmm/12/

var myMapLookup = {c:{ source:'a', target:'b'}};//this will map the line id to its source and target rectangles. this help you track which line is linked to which 2 rectangles.
function move(lineID, me) {
    //lineID will gve the id of the line.
    var nx = d3.event.x-parseInt(d3.select(me).attr("width"))/2
    var ny = d3.event.y-parseInt(d3.select(me).attr("height"))/2
    d3.select(me).attr('x', nx)
                   .attr('y', ny);
    //change the line's x and y on dragging
    //if source update the x1 and y1
    if(d3.select(me).attr('id') == myMapLookup.c.source){
        d3.select('#' + lineID).attr('x1', nx).attr('y1', ny);
    }
    //if source update the x2 and y2
    if(d3.select(me).attr('id') == myMapLookup.c.target){
        d3.select('#' + lineID).attr('x2', nx).attr('y2', ny);
    }

}

d3.select("#a").on('mousedown', function(d){
     d3.select("#c").style("display","");//make the line visible when mouse click is down.
    d3.select("#c").data({src: 'a', target: 'b'})
});
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);
//attach drag listener to all rectangles

    var dragA = d3.behavior.drag().on("drag", function(){move('c', this)});
    d3.select("#a").call(dragA);
    var dragB = d3.behavior.drag().on("drag", function(){move('c', this)});
    d3.select("#b").call(dragB);
});
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);

});

您可以使用myMapLookup来修改源和目标矩形的行。 通过这种方式,您可以拥有n个矩形,并且可以使用n行和相同的拖动代码。

相关问题