Skip to content

Instantly share code, notes, and snippets.

@yay
Last active March 2, 2018 16:16
Show Gist options
  • Save yay/55529bd17d8bf618dd2c750a92a9ff0c to your computer and use it in GitHub Desktop.
Save yay/55529bd17d8bf618dd2c750a92a9ff0c to your computer and use it in GitHub Desktop.
Animating 5000 circles with D3.
const width = 800;
const height = 400;
let data = [];
for (let i = 0; i < 5000; i++) {
data.push({
x: width * Math.random(),
y: height * Math.random(),
dx: Math.random() - 0.5,
dy: Math.random() - 0.5
});
}
let colorScale = d3.scaleOrdinal(d3.schemeCategory20);
// The 'div' here is some D3 selection of your choosing.
let svg = div.append('svg')
.attr('width', width)
.attr('height', height);
let circles = svg.append('g')
.selectAll()
.data(data)
.enter()
.append('circle')
.attr('r', 2 + Math.random())
.attr('fill', (d, i) => colorScale(i))
d3.timer(() => {
circles
.attr('cx', d => {
d.x += d.dx;
if (d.x > width) {
d.x -= width
} else if (d.x < 0) {
d.x += width;
}
return d.x;
})
.attr('cy', d => {
d.y += d.dy;
if (d.y > height) {
d.y -= height
} else if (d.y < 0) {
d.y += height;
}
return d.y;
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment