var width = 500; var height = 500; var margin = { top: 20, left: 20, bottom: 20, right: 20 }; var radius = 5; var svg = d3.select('#vis') .append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.right + ')'); width = width - margin.left - margin.right; height = height - margin.top - margin.bottom; var circle_data = [{ x: Math.random() * width, y: Math.random() * height, x_diff: Math.random() < 0.5 ? 1 : -1, y_diff: Math.random() < 0.5 ? 1 : -1, speed: Math.random() * 5, }]; var circles = svg.selectAll('.circle') .data(circle_data) .enter() .append('circle') .attr('class', 'circle') .attr('r', radius) .attr('fill', 'blue') .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }); d3.timer(animate); function animate(elapsed) { circles .attr('cx', function(d) { d.x = d.x + (d.speed * d.x_diff); if (d.x <= 0 || d.x >= width) { d.x_diff = d.x_diff * -1; } return d.x; }) .attr('cy', function(d) { d.y = d.y + (d.speed * d.y_diff); if (d.y <= 0 || d.y >= height) { d.y_diff = d.y_diff * -1; } return d.y; }); }