Skip to content

Instantly share code, notes, and snippets.

@maartenzam
Last active October 18, 2015 18:21
Show Gist options
  • Save maartenzam/f35baff17a0316ad4ff6 to your computer and use it in GitHub Desktop.
Save maartenzam/f35baff17a0316ad4ff6 to your computer and use it in GitHub Desktop.
1000 circles moving and bouncing of edges
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
#vis { width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="vis">
</div>
<script>
var width = document.getElementById("vis").clientWidth;
var height = document.getElementById("vis").clientHeight;
var svg = d3.select("#vis").append("svg")
.attr("width", width)
.attr("height", height)
move = function() {
var newx;
var newy;
var rand = Math.random();
if (d3.select(this).attr("cx") == 0) {
if (rand < 0.3333) {
newx = width;
newy = Math.random()*height;
}
else if (rand > 0.6666) {
newx = Math.random()*width;
newy = 0;
}
else {
newx = Math.random()*width;
newy = height;
}
};
if (d3.select(this).attr("cx") == width) {
if (rand < 0.3333) {
newx = 0;
newy = Math.random()*height;
}
else if (rand > 0.6666) {
newx = Math.random()*width;
newy = 0;
}
else {
newx = Math.random()*width;
newy = height;
};
};
if (d3.select(this).attr("cy") == 0) {
if (rand < 0.3333) {
newx = width*Math.random();
newy = height;
}
else if (rand > 0.6666) {
newx = 0;
newy = height*Math.random();
}
else {
newx = width;
newy = height*Math.random();
};
};
if (d3.select(this).attr("cy") == height) {
if (rand < 0.3333) {
newx = width*Math.random();
newy = 0;
}
else if (rand > 0.6666) {
newx = 0;
newy = height*Math.random();
}
else {
newx = width;
newy = height*Math.random();
};
};
d3.select(this)
.transition()
.duration(10000 + 20000*Math.random())
.ease("linear")
.attr("cy", newy)
.attr("cx", newx)
.each("end", move)
}
var i;
for (i = 1; i < 1000; i ++) {
var circle = svg.append("circle")
.attr("r", 2 + Math.random()*20)
.style("fill", "#9a0b16")
.style("opacity", 0.7);
circle.transition()
.delay(20*i)
.duration(10)
.attr("cy", 0)
.attr("cx", width*Math.random())
.each("end", move);
};
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment