This is an alternative way to move grouped data. Alternative to here.
Last active
February 17, 2017 14:02
-
-
Save mlrsoft/f62897f83503b4245ef87c6e014169ba to your computer and use it in GitHub Desktop.
d3.drag grouped elements in v4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.active { | |
stroke: #000; | |
stroke-width: 2px; | |
} | |
.rect { | |
pointer-events: all; | |
stroke: none; | |
stroke-width: 40px; | |
} | |
</style> | |
<body> | |
<script src="//d3js.org/d3.v4.min.js"></script> | |
<script> | |
var margin = {top: 10, right: 10, bottom: 30, left: 10}, | |
width = 960 - margin.left - margin.right, | |
height = 500 - margin.top - margin.bottom; | |
var rectangles = d3.range(10).map(function() { | |
return { | |
x: Math.round(Math.random() * (width)), | |
y: Math.round(Math.random() * (height)) | |
}; | |
}); | |
var color = d3.scaleOrdinal(d3.schemeCategory20); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width + margin.left + margin.right) | |
.attr("height", height + margin.top + margin.bottom); | |
var group = svg.selectAll('g') | |
.data(rectangles) | |
.enter().append("g") | |
.attr("transform",function(d) { | |
return "translate(" + (margin.left + d.x) + "," + (margin.top + d.y) + ")" | |
}) | |
.call(d3.drag() | |
.on("start", dragstarted) | |
.on("drag", dragged) | |
.on("end", dragended)); | |
group.append("rect") | |
.attr("height", 60) | |
.attr("width", 30) | |
.style("fill", function(d, i) { return color(i); }); | |
group.append("text") | |
.attr("text-anchor", "start") | |
.style("fill", "steelblue") | |
.text("Close"); | |
function dragstarted(d) { | |
d._drag = { | |
distance:0, | |
threshold:2, | |
initiated: false | |
}; | |
} | |
function dragged(d) { | |
if (!d._drag.initiated) { | |
d._drag.initiated = true; | |
d3.select(this).raise().classed("active", true); | |
} | |
d._drag.distance += d3.event.dx * d3.event.dx + d3.event.dy * d3.event.dy; | |
d.x = d3.event.x; | |
d.y = d3.event.y; | |
d3.select(this).attr('transform', 'translate('+[d.x,d.y]+')'); | |
} | |
function dragended(d) { | |
if (d._drag.distance < d._drag.threshold) { | |
d3.select(window).on('click.drag', null); | |
return; | |
} | |
d3.select(this).classed("active", false); | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment