Reputation: 102
I am trying to create a D3.js animation that does the following:
Rectangle starts with 0 width and expands to the right
Rectangle then contracts from the left
Repeat forever
I have created a simple animation using a recursive immediate function as demostrated in this example: http://bl.ocks.org/mbostock/1125997
function Sweep() {
var rect = d3.select(this);
(function repeat() {
rect = rect.transition()
.attr("x", function(){ return rect.attr("width") < width ? 0 : width; })
.attr("width", function () { return rect.attr("width") < width ? width : 0; })
.each("end", function () {
d3.select(this).attr("x", 0);
repeat();
});
})();
}
The recursion seems to be working correctly, however the line of code that resets x to 0 does not seem to work. I suspect this is a closure related issue, where the context inside the "end" callback is not what I expect.
The full code can be viewed here. http://jsfiddle.net/p3RZ7/
You will see that the first two iterations work, but nothing beyond that is visible because the x attribute is not reset.
Upvotes: 1
Views: 157
Reputation: 109232
The code for what you want to do is actually much easier than you think. You can do everything in your Sweep
function, including setting the x
attribute to 0:
function Sweep() {
d3.select(this).attr("x", 0)
.transition().ease("linear").duration(sweepDuration)
.attr("x", function(){ return d3.select(this).attr("width") < width ? 0 : width; })
.attr("width", function () { return d3.select(this).attr("width") < width ? width : 0; })
.each("end", Sweep);
}
Complete demo here.
Upvotes: 2