D3js reset the origin of a drag behaviour

狂风中的少年 提交于 2020-01-15 08:42:10

问题


I am trying to reset the drag behavior of a svg group. My requirement is to move the group from where it was stopped last. Here is my work fiddle. can some on help me?

<g id="a" transform="translate(0,0)">
    <g>
        <rect x="10" y="10" width="200" height="200" fill="red"></rect>
        <circle r="5" cx="10" cy="105" fill="blue"></circle>
        <circle r="5" cx="210" cy="105" fill="blue"></circle>
    </g>
    <g id="b" class="e" transform="translate(0,0)">
        <rect x="20" y="20" width="50" height="50" fill="black"></rect>
        <circle r="5" cx="20" cy="45" fill="blue"></circle>
        <circle r="5" cx="70" cy="45" fill="blue"></circle>
    </g>
    <g id="c" class="e" transform="translate(0,0)">
        <rect x="90" y="20" width="50" height="50" fill="black"></rect>
        <circle r="5" cx="90" cy="45" fill="blue"></circle>
        <circle r="5" cx="140" cy="45" fill="blue"></circle>
    </g>
</g>

<script>
    d3.select('#a').call(d3.behavior.drag().on('drag', function () {
        d3.select(this).attr('transform', 'translate(' + d3.event.x + ',' + d3.event.y + ')');
//        d3.event.stopPropagation();

    }));

    d3.selectAll('.e')
            .call(d3.behavior.drag()
                    .origin(function () {
                        var t = d3.select(this);
                        return {x: t.attr("x"), y: t.attr("y")};
                    }
                    )
                    .on('dragstart', function () {
                        d3.event.sourceEvent.stopPropagation();
                    })
                    .on('drag', function () {
                        console.log();
                        d3.select(this).attr('transform', 'translate(' + d3.event.x + ',' + d3.event.y + ')');
                    }))
                    .on('dragend', function () {
                        d3.select(this).call(d3.behavior.drag().origin(function () {

                            var t = d3.select(this);
                            return {x: t.attr("x"), y: t.attr("y")};
                        }))
                    })

    ;


</script>

回答1:


You need an origin function to do this. You have to add this before every drag in your SVG.

.origin(function() { var t = d3.select(this); return {x: t.attr("x") + d3.transform(t.attr("transform")).translate[0], y: t.attr("y") + d3.transform(t.attr("transform")).translate[1]}; })

Check the fiddle



来源:https://stackoverflow.com/questions/31768845/d3js-reset-the-origin-of-a-drag-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!