Reputation: 4849
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>
Upvotes: 2
Views: 808
Reputation: 576
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
Upvotes: 3