Transcript
[00:00] So I’ve got this groovy little animation of this ball bouncing around this box called container. And what I want to do is I want to say each time the ball hits the side of the box, I want the box to change color. So say container animate equals our container. And we’ll animate. Into that we’ll have our array of keyframes and then our timing object. So keyframes would be pretty simple. We’ll say border color. We’ll go with, let’s go with orange. And then our second keyframe be back to white. Pretty straightforward.
[00:44] We’ll say duration. This is where it’s kind of tricky because we want it to line up with our other animation. But what we can do in this case, since we know it’s going to hit it four times and there’s no offset or anything on the piece animate, we can just say 1500, which is the duration of our piece animation. And we can divide it by four. And then we’ll just say iterations, infinity. And let’s see. Oh, totally messed something up. Need a comma there. Cool. So that works.
[01:22] But now if this becomes 3500, we’ve got to change this to 3500. And if this is, you know, a lot of animations going on, it’s going to get kind of complicated. We may have, you know, what if we have a dozen of these? Now we’ve got to go change it in a dozen places. But if we say, you know, piece animation is kind of our source of truth. What we can do is we can get the piece animations effect property. And off of that, we can get computed timing. All right. And then we can just divide that by what we want. And whoops, not computed timing. Off of computed timing, we’re going to get the duration. So now save that. Everything is going to work exactly as it did. But if I come up here and change this to 5000, everything works and we don’t have to update the duration in a bunch of different places.
Sync animations perfectly without hardcoding durations. Master computed timing to keep your keyframe animations flexible and error-free.
<html><head> <style> body { background-color: #222; } .container { position: relative; width: 500px; height: 500px; border: 1px solid #fff; margin: 0 auto; } .piece { position: absolute; background-color: white; border-radius: 100%; width: 15px; height: 15px; } </style></head><body> <div class="container"> <div class="piece"></div> </div>
<script> const pieceKeyframes = [ { left: "50%", top: 0 }, { left: "calc(100% - 12px)", top: "50%" }, { left: "50%", top: "calc(100% - 12px)" }, { left: 0, top: "50%" }, { left: "50%", top: 0 } ];
const pieceAnimate = document.querySelector(".piece").animate( pieceKeyframes, { duration: 3500, iterations: Infinity } );
const containerAnimate = document.querySelector(".container").animate( [ { borderColor: "orange" }, { borderColor: "white" } ], { duration: pieceAnimate.effect.getComputedTiming().duration / 4, iterations: Infinity } ); </script></body></html>