Using d3 and React I have drawn a path. On this path I have multiple circles which are draggable only along that path. However, my current implementation only (sort of) works when there is one circle on that path.
(On dragStart it moves to length 0 on the path regardless of position, and whenever I'm dragging a second circle it starts of the the previous circle's position).
My question is: How can I drag multiple circles (or w.e) along a path in d3? Is there a way to get the currentLength position on the path based on cx and cy of the current circle?
var currentLength = 0;
class MyComponent extends Component {
constructor(props) {
super(props)
currentLength = 0;
}
componentDidMount() {
var drag = d3.behavior.drag()
.on('drag', this.move);
var g = d3.select(this._base);
var circle = g.selectAll('circle').data(this.props.data);
var onEnter = circle.enter();
onEnter.append('circle')
.attr({
r: 10,
cx: (d) => d.x,
cy: (d) => d.y
})
.style('fill', 'blue')
.call(drag);
}
move(d) {
currentLength += d3.event.dx + d3.event.dy
if (currentLength < 0) {
currentLength = 0
}
var pointAtCurrentLength = d3.select('#path').node().getPointAtLength(currentLength)
this.cx.baseVal.value = pointAtCurrentLength.x;
this.cy.baseVal.value = pointAtCurrentLength.y;
}
render() {
return <g ref={(c)=>this._base=c}></g>
}
}
Something similar to this, only draggable and multiple circles: http://bl.ocks.org/mbostock/1705868
Here's a quick modification to this example, which makes the circles draggable: