Skip to content

Instantly share code, notes, and snippets.

@vlandham
Forked from mbostock/.block
Created November 7, 2012 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlandham/4028954 to your computer and use it in GitHub Desktop.
Save vlandham/4028954 to your computer and use it in GitHub Desktop.
move letters
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: bold 100px monospace;
cursor: move;
}
.enter {
fill: green;
}
</style>
<body>
<script src="http://d3js.org/d3.v2.min.js?2.10.1"></script>
<script>
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(32," + (height / 2) + ")");
var drag = d3.behavior.drag()
.on("drag", dragmove);
function dragmove(d) {
d3.select(this)
.attr("x", d3.event.x)
.attr("y", d3.event.y);
}
function update(data) {
// DATA JOIN
// Join new data with old elements, if any.
var text = svg.selectAll("text")
.data(data, function(d) { return d; });
// UPDATE
// Update old elements as needed.
text.attr("class", "update")
.transition()
.duration(750)
.attr("x", function(d, i) { return i * 32; });
// ENTER
// Create new elements as needed.
text.enter().append("text")
.attr("class", "enter")
.attr("dy", ".15em")
.attr("y", 0)
.attr("x", function(d, i) { return i * 34; })
.style("fill-opacity", 1e-6)
.text(function(d) { return d; })
.call(drag)
.transition()
.duration(750)
.attr("y", function(d,i) { return randomFromInterval(-140, 140); })
.style("fill-opacity", 1);
// EXIT
// Remove old elements as needed.
text.exit()
.attr("class", "exit")
.transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
}
function randomFromInterval(from,to)
{
return Math.floor(Math.random()*(to-from+1)+from);
}
// The initial display.
update(alphabet);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment