Recursive/recurring animation events in D3

2020-03-24 06:09发布

问题:

I'm trying to make recurring transitions in D3 that will keep repeating indefinitely. Specifically, I'm working with a map and I want the background stars to occasionally flicker. The problem with transitions is that it appears they're all run ahead of time, so it will try to do the infinite recursion ahead of time and the page will never load. I found a related example (recursive d3 animation issue) that isn't infinite. My only other idea is to somehow use the d3 timer, but I'm not entirely sure how to go about that either. Any tips are appreciated.

回答1:

Right, you can’t schedule an infinite number of transitions ahead of time. :) However, you can repeatedly schedule a new transition when the old transition ends (or starts), using transition.each to listen for end (or start) events.

Take a look at the chained transitions example for an infinitely-repeating animation. Whenever a circle transition starts, it also schedules an identical following transition, allowing the transition to repeat indefinitely.

Alternatively, you could use setInterval or setTimeout to create transitions repeatedly, as in the concurrent transitions example. Unlike the chained transitions example I linked, this approach won’t guarantee exact synchronization of chained transitions, but if all you want is an occasional background flicker, it might be a slightly simpler approach.