JavaScript - - By Andrew Tetlaw

Star Wars Makes CSS3 Animations and Transformations Make Sense

atat-walker-css3Being a JavaScript guy, I was always uncomfortable with the whole idea of CSS animations. It’s an interesting experiment, but to me JavaScript is where your animation should be. That was until I found this AT-AT walker animation by Anthony Calzadilla.

Unfortunately, you’ll need a WebKit-based browser (Safari or Chrome, for example) to see it. So, sure it’s a WebKit proprietary CSS extension — the CSS3 animation and transformation modules are working drafts at the moment — but it’s always fun to experiment. And this experiment sure got me thinking.

But first, how is it done? Each part of the animation is separate; that is, the foot, shin, and thigh of each leg. CSS is then used to define the animation. Here’s the animation definition for the foot on Leg D, the front right one:

#atat #leg-d .leg-foot {
	-webkit-animation-name: foot-d;
	-webkit-animation-duration: 7s;
	-webkit-animation-iteration-count: infinite;
	-webkit-transform-origin: 50% 0;
}

It’s given a name, a duration (for how long the animation lasts), an iteration count (how many times the animation is run — infinitely in this case), and a position of origin. The next piece of the puzzle is the information for key frames:

@-webkit-keyframes foot-d {
  0% {
    -webkit-transform: rotate(0deg);
  }
  10% {
    -webkit-transform: rotate(-20deg);
  }
  30% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(0deg);
  }
}

With the @-webkit-keyframe at-rule you define the style rules to apply at certain stages of the animation duration. Here we have apply rules at the start of the animation (0%), when it’s 10% through, 30% through, and then when it’s finished (100%). In the case of this example, the -webkit-transform declaration is used to apply a rotation, although any CSS property could be applied.

By applying different degrees of rotation, for different animated parts at different times during the animation sequence, the illusion is almost like puppetry.

There’s also an alternative syntax to use inside a @-webkit-keyframe block; you can specify to and from values like so:

@-webkit-keyframes fade-in {
  from {
    color: #fff
  }
  to {
    color: #000
  }
}

What do you think? To me it looks like a really straightforward syntax for describing animation. But you know what would be really cool? If a jQuery plugin was written that could read CSS3 animation syntax and execute the animation, making it cross-browser compatible.

Now that would rock.

You can read more about CSS3 animations on the WebKit blog.

Sponsors