One approach, as suggested in the comments, might not be the ideal solution for your specific needs, but it is, in my view, the most straightforward and neat: rather than moving the circles individually, consider shifting the entire group that contains them, known as the <g>
element.
The equation for translating the group is quite simple:
.attr("transform", "translate(" + (w/2 - pX) + "," + (h/2 - pY) + ")")
Here, w
represents the SVG's width, h
is the height, pX
stands for the circle's x-coordinate, and pY
represents the circle's y-coordinate.
A basic demonstration is provided below. I have created 20 circles and, every 2 seconds, I select one circle at a time (in sequence) and center it, highlighting it in red:
var svg = d3.select("svg");
var g = svg.append("g")
var circles = g.selectAll(null)
.data(d3.range(20).map(function() {
return {
x: Math.random() * 500,
y: Math.random() * 300
}
}))
.enter()
.append("circle")
.attr("cx", function(d) {
return d.x
})
.attr("cy", function(d) {
return d.y
})
.attr("r", 10)
.style("fill", "lime");
var counter = 0;
var timer = d3.interval(function() {
if (counter === 19) {
timer.stop()
}
var thisCircle = circles.filter(function(d, i) {
return i === counter;
});
var position = thisCircle.datum();
g.transition()
.duration(1500)
.attr("transform", "translate(" + (250 - position.x) + "," + (150 - position.y) + ")");
thisCircle.style("stroke", "red").style("stroke-width", 4)
.transition()
.delay(2000)
.duration(0)
.style("stroke", "none")
counter++;
}, 2000)
svg {
border: 1px solid gray;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="300"></svg>
EDIT:
To trigger a similar action on click, you can employ the same concept. Below is a demo showcasing this functionality:
var svg = d3.select("svg");
var g = svg.append("g")
var circles = g.selectAll(null)
.data(d3.range(20).map(function() {
return {
x: Math.random() * 500,
y: Math.random() * 300
}
}))
.enter()
.append("circle")
.attr("cx", function(d) {
return d.x
})
.attr("cy", function(d) {
return d.y
})
.attr("r", 10)
.style("fill", "lime")
.style("cursor", "pointer");
circles.on("click", function(d) {
g.transition()
.duration(1000)
.attr("transform", "translate(" + (250 - d.x) + "," + (150 - d.y) + ")")
})
svg {
border: 1px solid gray;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="300"></svg>