Study of Drag Behavior
by Nivaldo
HTML
<!--
- references:
- http://bl.ocks.org/mbostock/6123708
- huge lesson: because the dragging is being called from the g, the transform needs to take into account the displacement of the circle from the origin of g (20,20; this is cx, cy); only if you do that the pointer will be in the right location ***AND*** the styling of the cursor will show...need a deeper understanding of that)
- if the drag is called from the circle, then the code inside dragged will be something like: d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y); also, the styling to red would work as well, but it will not drag the text...would have to be done separately
- if the circle is styled, it will have precedence of the styling of the g; the only way to paint the circle red is to not style it with anything (it will be black); this is why it works for the text, it is not styled
-->
CSS
.group circle {
fill: blue;
}
.group.dragging {
cursor: move;
fill: red;
}
JavaScript
var drag = d3.behavior.drag()
.on("dragstart",dragstarted)
.on("drag",dragged)
.on("dragend",dragended);
var svg = d3.select("body")
.append("svg");
var g = svg
.append("g")
.attr("class","group")
.call(drag);
var circle = g
.append("circle")
.attr("cx",20)
.attr("cy", 20)
.attr("r",10);
var text = g
.append("text")
.attr("x",30)
.attr("y",20)
.text("circle");
function dragged() {
d3.select(this)
.attr("transform", "translate(" + (d3.event.x - 20) + "," + (d3.event.y - 20) + ")");
};
function dragstarted() {
d3.event.sourceEvent.stopPropagation();
d3.select(this)
.classed("dragging",true);
};
function dragended() {
d3.select(this)
.classed("dragging",false);
};