Skip to content

Instantly share code, notes, and snippets.

@biovisualize
Created September 5, 2011 14:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biovisualize/1195063 to your computer and use it in GitHub Desktop.
Save biovisualize/1195063 to your computer and use it in GitHub Desktop.
Custom drag and drop with D3
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<title>Drag And Drop</title>
</head>
<body>
<div id="viz"></div>
<script type="text/javascript">
//-------------------------------------------------
// Functional draft of a dragAll plugin
//-------------------------------------------------
(function(){d3.experiments = {};
d3.experiments.dragAll = function() {
this.on("mousedown", function(){grab(this, event)})
.on("mousemove", function(){drag(this, event)})
.on("mouseup", function(){drop(this, event)});
};
var trueCoordX = null,
trueCoordY = null,
grabPointX = null,
grabPointY = null,
dragTarget = null;
function grab(element, event){
dragTarget = event.target;
//// send the grabbed element to top
dragTarget.parentNode.appendChild( dragTarget );
d3.select(dragTarget).attr("pointer-events", "none");
//// find the coordinates
var transMatrix = dragTarget.getCTM();
grabPointX = trueCoordX - Number(transMatrix.e);
grabPointY = trueCoordY - Number(transMatrix.f);
};
function drag(element, event){
var newScale = vizSVG.node().currentScale;
var translation = vizSVG.node().currentTranslate;
trueCoordX = (event.clientX - translation.x)/newScale;
trueCoordY = (event.clientY - translation.y)/newScale;
if (dragTarget){
var newX = trueCoordX - grabPointX;
var newY = trueCoordY - grabPointY;
d3.select(dragTarget).attr("transform", "translate(" + newX + "," + newY + ")");
}
};
function drop(element, event){
if (dragTarget){
d3.select(dragTarget).attr("pointer-events", "all");
var targetElement = event.target;
if(targetElement != vizSVG.node()){
console.log(dragTarget.id + ' has been dropped on top of ' + targetElement.id);
}
dragTarget = null;
}
};
})();
//-------------------------------------------------
// Example of use
//-------------------------------------------------
//// bind event to the root SVG
var vizSVG = d3.select("#viz")
.append("svg:svg")
.attr("width", 400)
.attr("height", 300)
.call(d3.experiments.dragAll);
vizSVG.append("svg:circle")
.attr("id", "blueCircle")
.attr("cx", 50)
.attr("cy", 140)
.attr("r", 40)
.attr("fill", "blue");
vizSVG.append("svg:rect")
.attr("id", "redRectangle")
.attr("x", 100)
.attr("y", 100)
.attr("width", 100)
.attr("height", 80)
.attr("fill", "red");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment