How can I run a transition continuously in D3.js?
For example, say I want to change the body
colour from red to blue and back again, continuously (I don't, that would be horrendous, but go with it).
This is how I would do it once:
d3.select("body").transition().duration(1000).style("background-color", "red");
How would I do it continuously?
The closest examples I have seen use d3.timer
, but I am not sure if there is a better way to do it.
You can use transition.each()
and the "end" event. The code would look something like the following.
function myTrans() {
d3.select("body").transition().duration(1000).style("background-color", "red")
.each("end", function() {
d3.select(this).transition().duration(1000).style("background-color", "blue")
.each("end", function() { myTrans(); });
});
}
You might want to check out this blog post (2 parts) on D3 transitions - http://blog.safaribooksonline.com/2013/07/11/reusable-d3-js-using-attrtween-transitions-and-mv/
I'm just beginning to work with D3 and this was helpful.
For D3 version 4 you have to use .on instead of .each (based on Lars answer):
function myTrans() {
d3.select("body").transition().duration(1000).style("background-color", "red")
.on("end", function() {
d3.select(this).transition().duration(1000).style("background-color", "blue")
.on("end", function() { myTrans(); });
});
}
I faced the same problem and I used css animations to solve the problem. With simple html and css would be like this:
#cube {
width: 120px;
height:120px;
animation-duration: 3s;
animation-name: transcolor;
animation-iteration-count: infinite;
animation-direction: alternate;
}
@keyframes transcolor {
from {
background-color:#535455;
}
to {
background-color:#bf2c23;
}
}
<div id="cube">
</div>
With d3 and javascript :
d3.select("body")
.style("animation", "transcolor 3s infinite linear alternate");
@keyframes transcolor {
from {
background-color:#535455;
}
to {
background-color:#bf2c23;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>