I have an image that swings using CSS rotate animation. I would like to stop it smoothly (and put it back to its original position when clicking on another element but without getting the jumpy stop feeling). It seems that the expected behaviour only happens on the first iteration of the animation but not on the upcoming ones (this is when clicking on the "slow" button during the first 2 seconds)
Here is a sample code https://jsfiddle.net/pbarrientos/5v3xwak6/
I have already tried adding animation-iteration-count: 1; and adding/removing classes.
var css = {
'-webkit-animation-iteration-count': "1",
'-moz-animation-iteration-count': "1",
'animation-iteration-count': "1"
}
Clues anyone?
I would use manual animation here. The browser is in charge of its CSS animation and it will be challenging to intervene with that with perfectly synced position and speed.
As the animation is not very complex we can simply set up our own matrix, or use the helper methods, as well as using a sine function where radius is reduced when stopped.
When hitting the stop button we reduce the radius to make it appear to be stopping. We can do the opposite to start again. The benefit is that we can stop at any point and have a natural rest. If you want to offset the angle you could interpolate to that angle at the same time as reducing radius.
By using
requestAnimationFrame
and transforms we will obtain smooth animation just like with CSS.The main function would be:
Then when stopping, reduce radius which will end up as angle:
Example
You may want to implement a mechanism to abort the loop as well when radius is lower than n, then start the loop when needed. Use a separate flag for that so the risk of starting several rAF's is eliminated.