Skip to content

Instantly share code, notes, and snippets.

@dvreed77
Created October 13, 2013 16:45
Show Gist options
  • Save dvreed77/6964373 to your computer and use it in GitHub Desktop.
Save dvreed77/6964373 to your computer and use it in GitHub Desktop.
Simple particles in box example!
<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<body>
</body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var w = 500,
h = 500,
t = 0,
last = 0,
dt,
x = d3.scale.linear().range([0, w]).domain([-2, 2]),
y = d3.scale.linear().range([h, 0]).domain([-2, 2]);
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var init_state = d3.range(100).map(function(d){
d = {}
d.cx = -2 + 4*Math.random();
d.cy = -2 + 4*Math.random();
d.vx = -1 + 2*Math.random();
d.vy = -1 + 2*Math.random();
return d;
})
var color = d3.scale.category20();
var circle = svg.selectAll("circle")
.data(init_state)
.enter()
.append("circle")
.attr("cx", function(d){ return x(d.cx); })
.attr("cy", function(d){ return y(d.cy); })
.attr("r", 3)
.style("fill-opacity", 0.8)
.style("fill", function(d,i){ return color(i); });
d3.timer(function(elapsed) {
dt = (elapsed - last)/1000;
t += dt;
last = elapsed;
step();
});
function step() {
d3.select("span.time")
.text("t=" + t.toFixed(2) + ", dt=" + dt);
circle.datum(function(d) {
d.cx += d.vx*dt;
d.cy += d.vy*dt;
if (d.cx < -2) {
d.vx *= -1
}
if (d.cx > 2) {
d.vx *= -1
}
if (d.cy < -2) {
d.vy *= -1
}
if (d.cy > 2) {
d.vy *= -1
}
return d;
});
circle
.attr("cx", function(d){ return x(d.cx); })
.attr("cy", function(d){ return y(d.cy); })
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment