d3.js占位符图形时拖动SVG元素



我正在为查询语言创建一个可视化编写器。我有3个不同的SVG矩形元素(说A->操作符,B->Some_Objects, C->绘图画布)。我想把元素从A、B拖到C。如果用户把元素从A/B拖到C,同样的元素应该在C中绘制,它也必须出现在A/B中。同时,如果用户没有删除c中的元素,它不应该做任何事情。

为了实现这一点,我尝试使用占位符技术(如jQuery UI)。但我不知道该怎么做。有人能帮我一下吗?

这是我到目前为止创建的UI。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="js/live.js"></script>
    <script src="js/d3.v3.min.js"></script>
</head>
<body>
<svg width="1024" height="768" style="background-color: #204d74">
    <!--<g>-->
        <rect x="10" y="20" height="250" width="300" style="fill: #080808"></rect>
        <rect class="drg" x="12" y="22" height="50" width="50" style="fill: #f0ad4e"></rect>
    <!--</g>-->
        <rect x="10" y="280" height="250" width="300" style="fill: #080808"></rect>
        <rect class="drg" x="12" y="282" height="50" width="50" style="fill: #f0ad4e"></rect>

        <rect x="320" y="20" height="510" width="690" style="fill: #080808"></rect>
</svg>
<script>
    function move() {
        d3.select(this)
//                                            .attr("transform", "translate(" + d3.event.x + "," + d3.event.y + ")");
                .attr('x', d3.event.x - parseInt(d3.select(this).attr("width")) / 2)
                .attr('y', d3.event.y - parseInt(d3.select(this).attr("height")) / 2)
        ;
        this.parentNode.appendChild(this);
    }
    d3.selectAll(".drg").style("fill","red").call(d3.behavior.drag().on('drag', move).origin(function() {
        var t = d3.select(this);
        return {x: t.attr("x"), y: t.attr("y")};
    }).on('dragend', function(d){
                console.log('end')

            })
    )

</script>
</body>
</html>

在dragEnd上,你必须找到当前的鼠标坐标,并基于它克隆当前被拖动的元素&重置原始元素x &y的位置。

创建了一个jsFiddle来显示它。检查一下

    .on('dragend', function(d){
            var elem = d3.select(this);
            elem.attr("x",elem.attr("initial-x"));
            elem.attr("y",elem.attr("initial-y"));
            console.log(elem.attr("x"));
            var mouseCoordinates = d3.mouse(this);
            if(mouseCoordinates[0] > 320) {
                //Append new element
                d3.select("svg").append("rect")
                .classed("drg", true)
                .attr("width", 50)
                .attr("height", 50)
                .attr("x", mouseCoordinates[0])
                .attr("y", mouseCoordinates[1])
                .style("fill", "green");
            }
    })

最新更新