Skip to content

Instantly share code, notes, and snippets.

@sidharrell
Last active April 11, 2019 04:56
Show Gist options
  • Save sidharrell/54b5003ddd1de5ef6edff0b0dd52aa3f to your computer and use it in GitHub Desktop.
Save sidharrell/54b5003ddd1de5ef6edff0b0dd52aa3f to your computer and use it in GitHub Desktop.
d3 bouncing ball
<!DOCTYPE html>
<meta charset="utf-8">
<title>D3 test</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
<body>
</body>
<script>
var acceleration = {"ddx": 0, "ddy": -10};
var circleData = [
{"x": 0, "y": 0, "dx": 50, "dy": 100, "r": 10, "fill": "red", "index": 1},
{"x": 0, "y": 0, "dx": 60, "dy": 90, "r": 8, "fill": "blue", "index": 2},
{"x": 0, "y": 0, "dx": 70, "dy": 80, "r": 9, "fill": "green", "index": 3}
];
function circleIndex(d) { return d.index; }
function update(time) {
var arrayLength = circleData.length;
for (var i = 0; i < arrayLength; i++) {
circleData[i].x = circleData[i].x + (time/1000)*circleData[i].dx;
circleData[i].y = circleData[i].y + (time/1000)*circleData[i].dy;
circleData[i].dx = circleData[i].dx + (time/1000)*acceleration.ddx;
circleData[i].dy = circleData[i].dy + (time/1000)*acceleration.ddy;
if (circleData[i].y < 0) {
circleData[i].dy *= -1;
}
if (circleData[i].x < 0 || circleData[i].x > 1000) {
circleData[i].dx *= -1;
}
}
svgContainer.selectAll("circle")
.data(circleData, circleIndex)
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return 500 - d.y; })
}
var svgContainer = d3.select("body").append("svg")
.attr("width", 1000)
.attr("height", 500)
.style("border", "1px solid black");
var circles = svgContainer.selectAll("circle")
.data(circleData, circleIndex)
.enter()
.append("circle");
var circleAttributes = circles
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return 500 - d.y; })
.attr("r", function (d) { return d.r; })
.attr("fill", function (d) { return d.fill; });
window.onload = function () {
d3.interval(function() {
update(10);
}, 10);
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment