【问题标题】:Connecting two rectangles in d3js在d3js中连接两个矩形
【发布时间】:2015-06-13 22:50:53
【问题描述】:

我正在尝试用 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" 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>

【问题讨论】:

    标签: javascript svg d3.js


    【解决方案1】:

    您的代码中的问题是您在鼠标移动时添加了新行,但您应该刚刚更新了该行。

    我已经为您发布的要求写了一个小提琴,还添加了 cmets 以寻求您的帮助。

    http://jsfiddle.net/cyril123/fy4cv1ab/6/

    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);
    
    });
    <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>

    【讨论】:

    • 谢谢。为 cmets +1。
    猜你喜欢
    • 1970-01-01
    • 2015-06-10
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多