How to move elements along with svg group
I have a circle that is added as I drag. I want the circle to move with the group when I move the group with the mouse
Here's what I tried which doesn't work:
//targetG is the group element
targetG.append("rect")
.attr("fill", "none")
.style("stroke", "black")
.style("stroke-width", "2px")
.attr("width", 200)
.attr("height", 200)
.style("fill", "white")
.call(
d3.behavior.drag()
.on('drag', moveRect).origin(function () {
var t = d3.select(this);
return {x: t.attr("x"), y: t.attr("y")};
}));
Here's the complete code in fiddle: http://jsfiddle.net/vk62y7un/
source to share
There are several small issues that need to be addressed.
Your function of decomposing translation components is split into.
translate = (translate.substring (0, translate.indexOf (")"))). split (",");
While this works in Chrome, it should be separated by a space for IE.
translate = (translate.substring(0, translate.indexOf(")"))).split(",");
if (translate.length === 1)
translate = translate[0].split(' ');
This circle was not tied to g because of this.
Your (container) drag event is attached to a rectangle inside g. This should be bound to g instead. Accordingly, drag and drop functions must manipulate the transform (translate) attribute, not x and y.
var targetG = svg.append("g")
.attr("transform", "translate(150,150)")
.call(
d3.behavior.drag()
.on('drag', moveRect).origin(function () {
...
and
function moveRect() {
d3.select(this)
.attr('transform', 'translate(' + d3.event.x + ' ' + d3.event.y +')');
}
The origin (for g now) must be the (parsed) attribute of the transform (translate) at the start of the drag.
....
var tc = d3.select(this).attr('transform').replace(/[a-z()]/g, '').split(' ');
if (tc.length === 1)
tc = tc[0].split(',')
return { x: Number(tc[0]), y: Number(tc[1]) };
}));
Please note: checking === 1 and splitting is so that it works in IE and Chrome.
Fiddle (works in IE and Chrome) - http://jsfiddle.net/3hyu6om8/
source to share
The problem is when you try to drag the rectangle, you don't select the circles. I made some changes and you can drag the circles around the rectangle.
Add this part to your code:
var groupAll = d3.behavior.drag()
.origin(Object)
.on("drag", function(d, i) {
var child = this;
var move = d3.transform(child.getAttribute("transform")).translate;
var x = d3.event.dx + move[0];
var y = d3.event.dy + move[1];
d3.select(child).attr("transform", "translate(" + x + "," + y + ")");
});
The complete code is here .
source to share