Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat an animation 2 or 3 times before easing it out

Tags:

css

animation

How can I repeat a spinning animation x times before easing it out ?

For instance :

#spin-please {
	background: green;
	width: 50px;
	height: 50px;
	animation: spin 3s infinite ease-in-out;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  49% {
    transform: rotate(359deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
<div id="spin-please">
</div>

My animation right now is not very smooth at all (as you can see between the 1st and 2nd rotation), and there is an easing between the 2 rotations, which I want only at the start of the first of the rotation and at the end of the second (or the third if I choose to go with an additional rotation).

Easing in ==> rotation 1 ==> rotation 2 ==> easing out

Is this doable with CSS ?

like image 256
QiMath Avatar asked Sep 20 '16 23:09

QiMath


2 Answers

Instead of repeating the animation infinite times, you can specify a number of repetitions like this:

animation: spin 3s 3 ease-in-out; /* 3secs, repeat 3 times */

See animation iteration count for more examples.

Also useful to see the animation short-hand docs to set all the properties at once (like your code does)

I am not sure what the desired outcome you are looking for but I modified the animation to display the spinning happening three times (with some reversal spin as well)

#spin-please {
  background: green;
  width: 50px;
  height: 50px;
  /* @keyframes duration | timing-function | delay | 
      iteration-count | direction | fill-mode | play-state | name 
    */
  animation: 1s 3 spin;
  animation-timing-function: ease-in, linear, ease-out;
}
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
<div id="spin-please">
</div>
like image 137
blurfus Avatar answered Nov 15 '22 11:11

blurfus


The problem is totally not because your animation isn't smooth, the problem with keyframes, according to this code

49% {
    transform: rotate(359deg);
  }
  50% {
    transform: rotate(0deg);
  }

Your animation have to do 360deg rotation in very short time which is 1% ( between 49% - 50%) for any animation-timing-function value your animation is not smooth, Try this code :

#spin-please {
	background: green;
	width: 50px;
	height: 50px;
	animation: spin 3s ease infinite;
}

@keyframes spin {
  0% {
    animation-timing-function: ease-out;
    transform: rotate(0deg);
}
50% {
    transform: rotate(180deg);
}
100% {
    animation-timing-function: ease-in;
    transform: rotate(360deg);
}
}
<div id="spin-please">
</div>
Remember you can change your animation-timing-function in your keyframes. more details about animation-timing-function.
like image 25
MMJ Avatar answered Nov 15 '22 11:11

MMJ