Skip to content

Instantly share code, notes, and snippets.

@d3noob
Last active January 31, 2018 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save d3noob/bf44061b1d443f455b3f857f82721372 to your computer and use it in GitHub Desktop.
Save d3noob/bf44061b1d443f455b3f857f82721372 to your computer and use it in GitHub Desktop.
Looping a transition in v4

This is a demonstration of looping transition chaining using d3.js v4.

The circle moves from left to right and then back again so that it starts and ends in the same state and then we instruct the transition code to repeat itself.

This graph is part of the code samples for the update to the book D3 Tips and Tricks to version 4 of d3.js.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 960)
.attr("height", 500);
function circleTransition() {
var timeCircle = svg.append("circle")
.attr("fill", "steelblue")
.attr("r", 20);
repeat();
function repeat() {
timeCircle
.attr('cx', 40) // position the circle at 40 on the x axis
.attr('cy', 250) // position the circle at 250 on the y axis
.transition() // apply a transition
.duration(2000) // apply it over 2000 milliseconds
.attr('cx', 920) // move the circle to 920 on the x axis
.transition() // apply a transition
.duration(2000) // apply it over 2000 milliseconds
.attr('cx', 40) // return the circle to 40 on the x axis
.on("end", repeat); // when the transition finishes start again
};
};
circleTransition();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment