Reputation: 2266
I am attempting to create an effect with svgjs. This effect requires, in my example, getting an item to zip back and forth, left to right to left. I also want it to float up and down slightly, with the up-and-down animation duration distinct from the left-and-right, so it doesn't look obvious to the user that there is a loop (i.e. I don't want there to be a single loop for both axes).
One thing I've tried (r
is a rect
):
// horizontal
r.animate({
duration: Math.random() * 4000 + 1000,
swing: true,
times: Number.MAX_SAFE_INTEGER
})
.attr({
x: width - 10
})
// vertical
r.animate({
duration: Math.random() * 4000 + 1000,
swing: true,
times: Number.MAX_SAFE_INTEGER
})
.attr({
y: r.y() + (Math.random() * 250) - 125
})
With this code, the vertical animation never occurs because it is waiting for the horizontal loops to finish (which will effectively never happen).
I also tried this:
// horizontal
r.animate({
duration: Math.random() * 4000 + 1000,
swing: true,
times: Number.MAX_SAFE_INTEGER
})
.attr({
x: width - 10,
y: r.y() + (Math.random() * 250) - 125
})
It works but looks boring/awkward, because the loop-ness is transparent to the viewer.
(Incidentally, if you can suggest a way to get these loops to last forever, other than setting times: Number.MAX_SAFE_INTEGER
I'd be obliged, because that feels sloppy.)
Upvotes: 0
Views: 347
Reputation: 8474
You need to schedule the animations to start at the same time. You can do that by passing the keyword when: 'absolute'
to animate()
which tells the runner to be scheduled at an absolute time on the timeline. Since both runners (aka calls to animate) are from the same element, they get scheduled on the same timeline. You can also use now
as an alternative which basically stands for: start right now. But in that case it can happen that both of the animations are a few milliseconds apart.
Also you can use times: true
or times: Infinity
or just call loop(true, true)
r.animate({when: 'absolute', delay: 0, ...}) // 0 is time on the timeline, can be dropped
r.animate({when: 'absolute', delay: 0, ...})
You can also pass this as multiple arguments and as I mentioned use loop
:
r.animate(Math.random() * 4000 + 1000, 0, 'absolute').loop(true, true) // loop(times, swing)
Upvotes: 1