How can I start CSS3 Animations at a specific spot?
Asked Answered
A

2

15

I'm using CSS3 Animations, and I want to be able to move to a specific spot in the animation. For instance, if the CSS looks like this (and pretend that I used all the proper prefixes):

@keyframes fade_in_out_anim {
  0% { opacity: 0; }
  25% { opacity: 1; }
  75% { opacity: 1; }
  100% { opacity: 0; }
}
#fade_in_out {
  animation: fade_in_out_anim 5s;
}

then I would like to be able to stop the animation, and move it to the 50% mark. I guess that the ideal JavaScript would look something like this:

var style = document.getElementById('fade_in_out').style;
style.animationPlayState = 'paused';

// Here comes the made up part...
style.animation.moveTo('50%'); // Or alternately...
style.animationPlayPosition = '50%';

Does anyone know of a way to make this happen (hopefully in Webkit)?

Aberrant answered 10/5, 2012 at 19:15 Comment(2)
Can you provide more information on what you're goal is? Because if you just want to start an animation at the half-way point, I'd recommend two animations, one starting at 50% and one the full effect, then choose between them using classes.Manille
I want to be able to create a slider or touch interaction that will let the user scrub along an animation. I've settled on breaking the animation into stages until I find out how to do what I need.Aberrant
G
38

We can use the animation-delay property. Usually it delays animation for some time, and, if you set animation-delay: 2s;, animation will start two seconds after you applied the animation to the element. But, you also can use it to force it to start playing animation with a specific time-shift by using a negative value:

.element-animation{
animation: animationFrames ease 4s;
animation-delay: -2s;
}

http://default-value.com/blog/2012/10/start-css3-animation-from-specified-time-frame/

Gall answered 3/12, 2012 at 16:10 Comment(2)
This should be the selected answer. It's easy to implement and is clear.Lillianalillie
except then you cannot delay the startChitchat
T
1
  1. Get the animation object affecting the element
  2. Get it's duration
  3. Set the Animation object's currentTime to half of the duration value (since you want to set the progress to 50%)
let anim = fade_in_out.getAnimations()[0];
let duration = anim.effect.getTiming().duration;  
anim.currentTime = duration / 2;
Turbo answered 7/12, 2023 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.