[D3.js advanced series-6.0] Drag and drop applications (Drag) and d3.jsdrag
Drag (Drag) is an important interactive method. This article describes how to use Drag and drop.
1. Definition of drag
D3.behavior. drag () can be used in D3 to define the drag behavior.
var drag = d3.behavior.drag().on("drag", dragmove); function dragmove(d) {d3.select(this) .attr("cx", d.cx = d3.event.x ) .attr("cy", d.cy = d3.event.y );}
Row 2nd indicates that the dragmove function is called when a drag event occurs. In addition to the drag event, there are also dragstart and dragend events, which have been described in Chapter 2.1 of the advanced section.
In dragmove (), the d3.event. x and d3.event. y variables appear, which are the positions of the current mouse. We will draw the circle next to it, which means to re-draw the circle to the place where the current mouse is located.
2. Draw circles
I believe everyone is familiar with the method of drawing circles. Finally, use the call function in the circle selection set to call the drag behavior just defined. The call function is used as a parameter to pass the set itself to the drag function.
Var circles = [{cx: 150, cy: 200, r: 30}, {cx: 250, cy: 200, r: 30},]; var svg = d3.select ("body "). append ("svg "). attr ("width", width ). attr ("height", height); svg. selectAll ("circle "). data (circles ). 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 ("fill", "black "). call (drag); // The drag behavior just defined
3. Results
The result is as follows:
Click the following link to view the source code:
Http://www.ourd3js.com/demo/J-6.0/drag.html
Thank you for reading.
Document Information
- Copyright Disclaimer: BY-non-commercial (NC)-deduction prohibited (ND)
- Published on: February 1, December 27, 2014
- More content: OUR D3.JS-data visualization special site and CSDN personal blog
- Note: This article is published in OUR D3.JS. For more information, see the source. Thank you.