Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 9, 2016 00:51
Show Gist options
  • Save mbostock/1371412 to your computer and use it in GitHub Desktop.
Save mbostock/1371412 to your computer and use it in GitHub Desktop.
Circles
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var w = 960,
h = 500;
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var circle = svg.selectAll("circle")
.data(d3.range(1000).map(function() {
return {
x: w * Math.random(),
y: h * Math.random(),
dx: Math.random() - 0.5,
dy: Math.random() - 0.5
};
}))
.enter().append("circle")
.attr("r", 2.5);
var text = svg.append("text")
.attr("x", 20)
.attr("y", 20);
var start = Date.now(),
frames = 0;
d3.timer(function() {
// Update the FPS meter.
var now = Date.now(), duration = now - start;
text.text(~~(++frames * 1000 / duration));
if (duration >= 1000) frames = 0, start = now;
// Update the circle positions.
circle
.attr("cx", function(d) { d.x += d.dx; if (d.x > w) d.x -= w; else if (d.x < 0) d.x += w; return d.x; })
.attr("cy", function(d) { d.y += d.dy; if (d.y > h) d.y -= h; else if (d.y < 0) d.y += h; return d.y; });
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment