I get the impression this question is so simple nobody has bothered to make a demo of it, but I don\'t know enough D3 (yet) to see what I\'m doing wrong. The behavior I\'m look
First off, you definitely have the right idea for how to add points on mousedown. The two things I'd change are:
click instead of mousedown, so if you click existing points you don't add a new point on top of the existing one.click.Here's a working click function:
function click(){
// Ignore the click event if it was suppressed
if (d3.event.defaultPrevented) return;
// Extract the click location\
var point = d3.mouse(this)
, p = {x: point[0], y: point[1] };
// Append a new point
svg.append("circle")
.attr("transform", "translate(" + p.x + "," + p.y + ")")
.attr("r", "5")
.attr("class", "dot")
.style("cursor", "pointer")
.call(drag);
}
Then, when dragging, it is simplest to move a circle using translate (which is also why I
use translate when creating points above). The only real step is to extract the drag's x and y locations. Here's a working example of drag behavior.
var drag = d3.behavior.drag()
.on("drag", dragmove);
function dragmove(d) {
var x = d3.event.x;
var y = d3.event.y;
d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
}
I put all this together in this jsfiddle.
Finally, here's a relevant SO question I read when constructing the drag example: How to drag an svg group using d3.js drag behavior?.