d3 draggable object example #1 – standalone
Table of Contents
1. Introduction
Creating a draggable object in d3. Followed guide originally here (sadly now-broken link): http://ssun.azurewebsites.net/creating-a-draggable-object-in-d3
.org
source for this file is here: index-src.html
2. Try it here
3. Prerequisites
- A directory tree
$HTTP_ROOT
that you can visit in a browser or serve via http. I'm using$HOME/proj/public_html/org-howto
, for example Mike Bostock's
d3
installed in$HTTP_ROOT/ext/d3
:ls -l $HOME/proj/public_html/org-howto/ext/d3
total 336 -rw-rw-r-- 1 roland roland 151725 Mar 12 00:06 d3.v3.min.js
Optionally, a webserver making
$HTTP_ROOT
available over http, for example:cd $HOME/Dropbox/public_html python -m SimpleHTTPServer 8080
When this is in place,
we should be able to bring up d3.js
in a browser here: http:/ext/d3/d3.js
4. Procedure
4.1. Create skeleton html file
This is the file browser will load to deliver our example.
Create drag-example.html
.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type="text/javascript" src="/ext/d3/d3.v3.min.js"></script> <script type="text/javascript" src="drag-example.js"></script> </head> <body> <div id="frame"></div> <script type="text/javascript"> window.onload = function() { ex.start(this); } </script> </body> </html>
4.2. Create javascript file drag-example.js
Create drag-example.js
.
This is where our d3
code lives.
!function() { var ex = {}; var box_width = 800; var box_height = 400; ex.start = function(w) { "use strict"; var box = (d3.select("#frame") .append("svg") .attr("class", "box") .attr("width", box_width) .attr("height", box_height) ); var circle = null; var drag = d3.behavior.drag() .on("dragstart", function() { circle.style("fill", "red"); }) .on("drag", function() { circle.attr("cx", d3.event.x).attr("cy", d3.event.y); }) .on("dragend", function() { circle.style("fill", "black")}); circle = box.selectAll(".draggableCircle") .data([{x: (box_width / 2), y: (box_height / 2), r: 25}]) .enter() .append("svg:circle") .attr("class", "draggableCircle") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", function(d) { return d.r; }) .call(drag) .style("fill", "black"); console.log("w=", w, ",this=", this); } this.ex = ex; }();