Skip to content

Instantly share code, notes, and snippets.

@SandeepTuniki
Last active December 2, 2016 10:02
Show Gist options
  • Save SandeepTuniki/953b39e0a1f0e3f32e505ebe2d0af106 to your computer and use it in GitHub Desktop.
Save SandeepTuniki/953b39e0a1f0e3f32e505ebe2d0af106 to your computer and use it in GitHub Desktop.
Moving circles
<html>
<head></head>
<body>
<svg width="960" height="500"></svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
<script src="index.js"></script>
</body>
</html>
var svg = d3.select("svg");
var width = +svg.attr("width");
var height = +svg.attr("height");
var color = d3.scaleOrdinal(d3.schemeCategory10);
var data = _.times(50, function () {
return getRadius();
});
function drawGraph() {
var circle = svg.selectAll("circle")
.data(data);
circle.exit().transition()
.attr("r", 0)
.remove();
circle.enter().append("circle")
.attr("cx", function() {
return getPos(width);
})
.attr("cy", function() {
return getPos(height);
})
.attr("r", 0)
.attr("fill",function(d,i){return color(i);})
.transition()
.attr("r", function(d) {
return d;
});
circle.merge(circle)
.transition()
.duration(1000)
.attr("r", function(d) {return d})
.attr("cx", function(d) { return getPos(width)})
.attr("cy", function(d) { return getPos(height)})
}
window.setInterval(function() {
var dice = _.random(1, 3);
var newRadius = getRadius();
var index = _.random(0, data.length - 1);
if (dice === 1) {
data.push(newRadius);
} else if (dice === 2) {
data.splice(index, 1);
} else if (dice === 3) {
data[index] = newRadius;
}
drawGraph();
}, 1000);
function getRadius() {
return _.random(5, 15);
}
function getPos(upperLimit) {
return _.random(10, upperLimit)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment