Drag-and-drop (Drag) is an important part of interactivity, and this article explains how to use it.
1. Definition of drag
D3.behavior.drag () can be used in D3 to define 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);}
Line 2nd indicates that the DragMove function is called when the drag event occurs. In addition to the drag event, there are DragStart and Dragend events, which have been described in "advanced-Chapter 2.1".
In DragMove (), there are two variables of d3.event.x and D3.EVENT.Y, which is the position of the current mouse. We'll draw the circle behind us, which means to redraw the circle to the current mouse position.
2. Draw a Circle
The method of drawing circles is believed to be familiar to everyone. Finally, the call function is used in the circle selection, and the drag behavior just defined is called. The call function, as we said earlier, is going to select the set itself as a parameter and pass it 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 ("Widt H ", 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); Here's the drag behavior that you just defined.
3. Results
As a result, drag and drop to try:
Source code click on the following link to view:
Http://www.ourd3js.com/demo/J-6.0/drag.html
Thank you for reading.
Document Information
- Copyright Notice: Attribution (by)-Non-commercial (NC)-No deduction (ND)
- Published: December 27, 2014
- More content: our D3. JS-Data Visualization special station and CSDN personal blog
- Remark: This article is published in our D3. JS, reproduced please indicate the source, thank you
"D3.js Advanced Series-6.0" Drag application (Drag)