Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from mbostock/.block
Last active December 1, 2017 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mbostock/2647924 to your computer and use it in GitHub Desktop.
Save mbostock/2647924 to your computer and use it in GitHub Desktop.
SVG Swarm
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<title>SVG Swarm</title>
<style>
svg {
position: absolute;
top: 0;
}
circle {
fill: steelblue;
stroke: #666;
stroke-width: 1.5px;
}
</style>
<div id="fps">FPS: <span>?</span></div>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var data = d3.range(500).map(function() {
return {xloc: 0, yloc: 0, xvel: 0, yvel: 0};
});
var width = 960,
height = 500;
var x = d3.scale.linear()
.domain([-5, 5])
.range([0, width]);
var y = d3.scale.linear()
.domain([-5, 5])
.range([0, height]);
var time0 = Date.now(),
time1;
var fps = d3.select("#fps span");
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var circle = svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", 10)
.attr("cy", 10)
.attr("r", 1);
d3.timer(function() {
data.forEach(function(d) {
d.xloc += d.xvel;
d.yloc += d.yvel;
d.xvel += 0.04 * (Math.random() - .5) - 0.05 * d.xvel - 0.0005 * d.xloc;
d.yvel += 0.04 * (Math.random() - .5) - 0.05 * d.yvel - 0.0005 * d.yloc;
});
circle
.attr("transform", function(d) { return "translate(" + x(d.xloc) + "," + y(d.yloc) + ")"; })
.attr("r", function(d) { return Math.min(1 + 1000 * Math.abs(d.xvel * d.yvel), 10); });
time1 = Date.now();
fps.text(Math.round(1000 / (time1 - time0)));
time0 = time1;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment