Skip to content

Instantly share code, notes, and snippets.

@satomacoto
Created December 11, 2012 03:31
Show Gist options
  • Save satomacoto/4255719 to your computer and use it in GitHub Desktop.
Save satomacoto/4255719 to your computer and use it in GitHub Desktop.
D3 random particles
<html>
<head>
<title>
</title>
<script src="http://d3js.org/d3.v2.js"></script>
</head>
<body>
<script type="text/javascript">
var w = 500;
var h = 500;
var barpadding = 1;
var color = d3.scale.category20();
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var dataset = [];
var N = 20;
var T = 10;
for (var i = 0; i < N; i++) {
data = [];
for (var j = 0; j < T; j++) {
var d = {};
d.x = Math.random() * w;
d.y = Math.random() * h;
d.color = color(Math.random() * 20)
data.push(d);
}
dataset.push(data);
}
var circles = svg.selectAll("circle")
.data(dataset[0])
.enter()
.append("circle")
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.attr("fill", function(d) {
return d.color;
})
.attr("r", 5);
var t = 0;
var move_step = function(step) {
t += step
if (T <= t)
t = T - 1
else if (t < 0)
t = 0
data = dataset[t];
circles.each(function(d, i){
d3.select(this).transition().attr("cx", data[i].x).attr("cy", data[i].y).attr("fill", data[i].color);
});
};
</script>
<button id="previous" onclick="move_step(-1);"><</button>
<button id="next" onclick="move_step(1);">></button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment