Skip to content

Instantly share code, notes, and snippets.

@adilapapaya
Last active August 29, 2015 13:57
Show Gist options
  • Save adilapapaya/9379338 to your computer and use it in GitHub Desktop.
Save adilapapaya/9379338 to your computer and use it in GitHub Desktop.
Bouncing Blocks for Bl.ocks.org

A true time-waster. If it's any consolation, I wasted more time making it than you did watching it play out. :)

<!DOCTYPE html>
<meta charset="utf-8">
<style>
html,
body {
position: relative;
height: 100%;
margin: 0;
}
#the-blocks {
width: 800px;
margin:200px auto;
background:#000000;
}
.blocks rect{
fill:#eeeeee;
stroke:#aaaaaa;
}
.blocks text{
font-size:14px;
font-variant:small-caps;
text-align:center;
}
svg{
text-align:center;
}
</style>
<body>
<!-- blocks go in here -->
<div id = 'the-blocks'>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type='text/javascript'>
var s = 'a painfully slow to load string';
var w = 800,
h = 100,
x = d3.scale.ordinal().domain(d3.range(s.length)).rangePoints([20, w - 40]),
t = Date.now(),
ln = s.length;
var data = [];
var i=-1; while(++i<ln){
data.push({letter:s[i],id:i})
}
var svg = d3.select('#the-blocks').append("svg")
.attr("width", w)
.attr("height", h);
var blocks = svg.append("g")
.attr("class", "blocks")
.selectAll(".block")
.data(data);
blocks.enter().append("g")
.attr("class", "block")
.attr("transform", function(d,i) {
return "translate("+(x(d.id))+","+(-100)+")"
+"rotate("+rotate(d,i)+")";
})
var nonSpace = blocks.filter(function(d){
return d.letter!=' ';
})
nonSpace.append("rect")
.attr("width", 30)
.attr("height",30)
nonSpace.append("text")
.attr("x",13).attr("y",15)
.attr("dy", ".3em")
.text(function(d){ return d.letter; });
var t1 = 500, t2 = 5000;
nonSpace.transition()
.ease("bounce")
.delay(function(d,i){ return t1*d.id; })
.duration(t2)
.attr("transform", function(d,i) {
return "translate("+x(d.id)+","+(h-42)+")"
+"rotate("+rotate(d,i)+")";
})
function rotate(d,i){
return Math.random()*(d.id%2 - .5) * 20;
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment