Skip to content

Instantly share code, notes, and snippets.

@seliopou
Created November 20, 2012 03:12
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 seliopou/4115711 to your computer and use it in GitHub Desktop.
Save seliopou/4115711 to your computer and use it in GitHub Desktop.
d3.js animation pattern
<!DOCTYPE html>
<html>
<head>
<title>d3.js animation pattern</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://d3js.org/d3.v2.js"></script>
<script type="text/javascript" src="vis.js"></script>
<style type="text/css">
body {
font-family: "Helvetica Neue", Helvetica, sans-serif
}
h1 {
font-weight: 300;
margin-left: 2em;
}
.bar {
fill: rgba(51, 51, 51, 0.5);
}
</style>
</head>
<body>
<h1><a href="http://en.wikipedia.org">Click here</a>, and then hit the Back Button (no animation)</h1>
<div id="canvas"></div>
<form>
<input id="back_detect" type="hidden" name="back_detect" />
</form>
</body>
<script type="text/javascript">
/* Render vis, animating only if the value of the field is "" */
vis("#canvas", $("#back_detect").val() == "");
/*
* Set the value of the form field to "visited". Most browsers will preserve
* this when the user navigates with the back button.
*/
$("#back_detect").val("visited");
</script>
</html>
function vis(selection, animate) {
var width = 960,
height = 401;
var x = d3.scale.ordinal().domain([0, 1])
.rangeBands([0, width], 0.1);
var y = d3.scale.ordinal().domain([0, 1, 2, 3, 4, 5])
.rangeBands([height, 0], 0.2);
// The initial and final value of animated elements
var bar_y = {
'initial' : height,
'final' : function(d) { return y(d[1]); }
};
var canvas = d3.select(selection)
.append('svg:svg')
.attr('width', width)
.attr('height', height);
var bars = canvas.selectAll('cols')
.data([[0, 1, 2], [0, 1, 2, 3, 4, 5]])
.enter().append('svg:g').selectAll('bars')
.data(function(d, i) {
return d.map(function(e) { return [i, e]; });
})
.enter().append('svg:rect')
.attr('class', 'bar')
.attr('width', x.rangeBand())
.attr('height', y.rangeBand())
.attr('x', function(d) { return x(d[0]); })
.attr('y', bar_y[animate ? 'initial' : 'final'])
if (animate) {
bars.transition()
.duration(1000)
.attr('y', bar_y['final'])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment