Skip to content

Instantly share code, notes, and snippets.

@pvernier
Last active March 11, 2018 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pvernier/96ec02fe9e53e63603191988ffbd1e1e to your computer and use it in GitHub Desktop.
Save pvernier/96ec02fe9e53e63603191988ffbd1e1e to your computer and use it in GitHub Desktop.
Randomly add circles to fill in a stack
license: gpl-3.0
height: 200

Randomly add 100 circles to fill in a stack using d3-timer (d3.interval)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
svg {
background-color: #4d4d4d;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<svg></svg>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-timer.v1.min.js"></script>
<script type="text/javascript">
function getRandomX() {
// Return a random index of the array coordsX
var index = Math.floor((Math.random() * coordsX.length));
return index
}
var coordsX = [10, 30, 50, 70, 90, 110, 130, 150, 170, 190]
var levelY = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
var interpolate = d3.interpolateRgb("steelblue", "brown");
var svg = d3.select("svg")
var i = 1;
var t = d3.interval(function(elapsed) {
// The column where to add a circle
var pick = getRandomX()
svg.append("circle")
.attr("cx", coordsX[pick])
.attr("cy", -10)
.attr("r", 10)
.transition()
.duration(1000)
.attr("cy", 200 - levelY[pick])
.style("fill", interpolate(levelY[pick]/190))
if (levelY[pick] == 190) { // If column is full
coordsX.splice(pick, 1);
levelY.splice(pick, 1);
}
else {
levelY[pick] = levelY[pick] + 20
}
i = i + 1
if (i == 101) t.stop(); // Stop after adding the 100th circle
}, 200);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment