Skip to content

Instantly share code, notes, and snippets.

@saifuddin778
Last active June 26, 2016 06:19
Show Gist options
  • Save saifuddin778/4f78f8abad52638862ac3507e4a43901 to your computer and use it in GitHub Desktop.
Save saifuddin778/4f78f8abad52638862ac3507e4a43901 to your computer and use it in GitHub Desktop.
Chained Transitions

This type of chained transition can be better understood as a ping-pong process: function A changes/moves some objects, and calls function B (A throws the ball at B). In return B changes/moves some objects, and calls function A (B throws the ball at A). This process keeps on going, until (of course) some interruption does happen.

This example transitions some random boxes in this fashion.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.box {
stroke: crimson;
stroke-width: 0.7;
opacity: 0.3;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var width = 960;
var height = 503;
var n = 15;
var space = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var colors_a = d3.scale.linear()
.interpolate(d3.interpolateHcl)
.domain([0, n])
.range(['cornflowerblue', '#87D37C']);
var colors_b = d3.scale.linear()
.interpolate(d3.interpolateHcl)
.domain([0, n])
.range(['violet', 'lightblue']);
var nodes = d3.range(n).map(function(d, i){
return {
x: Math.random() * width,
y: Math.random() * height,
width: 100,
height: 100,
};
});
space.selectAll()
.data(nodes)
.enter()
.append("rect")
.attr("class", "box")
.attr("width", function(d){return d.width})
.attr("height", function(d){return d.height})
.attr("x", function(d){return d.x})
.attr("y", function(d){return d.y})
.style("fill", "white");
function random_a(){
d3.selectAll("rect")
.transition()
.duration(2000)
.attr("x", function(d){ return d.x * Math.random()})
.attr("y", function(d){ return d.y * Math.random()})
.style("fill", function(d, i){ return colors_a(Math.ceil(n * Math.random())) })
.each("end", random_b);
}
function random_b(){
d3.selectAll("rect")
.transition()
.duration(2000)
.attr("x", function(d){ return d.x * Math.random()})
.attr("y", function(d){ return d.y * Math.random()})
.style("fill", function(d, i){ return colors_b(Math.ceil(n * Math.random())) })
.each("end", random_a);
}
random_a();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment