I'm trying to use d3 to make a circle that is draggable, but leaves a copy of the original in place. Here is the circle:
g.selectAll('circle')
.data([{
cx: 90,
cy: 80,
r: 30 }])
.enter().append('circle')
.attr('cx', function (d) {return d.cx})
.attr('cy', function (d) {return d.cy})
.attr('r', function(d) {return d.r})
.attr('class','original')
.call(dragOriginal);
Here is the drag behavior:
var dragOriginal = d3.behavior.drag()
.on('dragstart', cloneSpeciesMaker)
.on('drag', function (d, i) {
d.cx += d3.event.dx;
d.cy += d3.event.dy;
d3.select(this).attr('cx', d.cx).attr('cy', d.cy)
});
And here is the dragstart function:
function cloneSpeciesMaker(d) {
var svg = d3.select('svg');
//original becomes copy
d3.select(this)
.classed('original',false)
.attr('class','copy');
// creates new 'original' in place
var data = [{cx:d.cx,cy:d.cy,r:d.r}];
svg.append('circle')
.data(data)
.attr('class','original')
.attr("cx",function(d) {return d.x})
.attr("cy",function(d) {return d.y})
.attr("r",function(d) {return d.r})
.style("fill","purple")
.attr("class","original")
.call(dragOriginal);
}
Right now, I'm succeeding in making the original circle become a 'copy' and dragging it around, but it the part where I append a new circle in its old place isn't working, can anyone explain why?
One problem I can see from the code is in this section:
function cloneSpeciesMaker(d) {
var svg = d3.select('svg');
//original becomes copy
d3.select(this)
.classed('original',false)
.attr('class','copy');
// creates new 'original' in place
var data = [{cx:d.cx,cy:d.cy,r:d.r}];
svg.append('circle')
.data(data)
.attr('class','original')
.attr("cx",function(d) {return d.x})
.attr("cy",function(d) {return d.y})
.attr("r",function(d) {return d.r})
.style("fill","purple")
.attr("class","original")
.call(dragOriginal);
}
You are setting the data like this
var data = [{cx:d.cx,cy:d.cy,r:d.r}];
But you are doing which is incorrect dx and dy is not defined by you in data.
.attr("cx",function(d) {return d.x})
.attr("cy",function(d) {return d.y})
This should have been:
.attr("cx",function(d) {return d.cx})
.attr("cy",function(d) {return d.cy})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.