Today’s HTML5 applications can provide awesome experiences thanks to the new CSS3 specifications. One of them is CSS3 Animations. It can help you building rich animations on HTML elements. This can provide interesting feedbacks to the users and enables fast & fluid UIs. As those new animations are most of the time hardware accelerated by the GPU, they definitely raise the quality bar of the new generation of HTML5 applications.
According to the “CSS Animation Module Level 3” specification on the W3C site, CSS3 Animations introduces defined animations, which specify the values that CSS properties will take over a given time interval. This specification is an extension to CSS Transitions.
As CSS3 Animation is an extension to CSS3 Transitions, you should first read the article of my colleague David Catuhe on Transitions here: Introduction to CSS3 Transitions.
You can test this sample also in a separate window here: http://david.blob.core.windows.net/html5/css3atat/index.htm
Note: this sample has been tested successfully with native animations under IE10 PP3/PP4, Chrome 15, Firefox 8 & iPad 2 and with JS fallback under IE9 desktop & mobile (Windows Phone). For an unknown reason, it behaves in weird way under Opera 11.50 but works fine with the 11.60. Moreover, our lovely blogging platform is most of the time forcing the IE9 rendering engine via a meta tag. To force it back to the IE10 standards mode, press the F12 key and change the value of “Document Mode” back to IE10. Otherwise, view the demo in a separate window.
This sample is based on the awesome work done by Anthony Calzadilla. You can check other incredible demos on his website here: http://www.anthonycalzadilla.com . I’m a huge fan of the I twitty the fool sample using SVG & CSS3 Animation for instance.
Let’s first review on what you can play to build the animations. CSS3 Animations works basically on the same values as CSS3 Transition.
Here they are:
- color: interpolated via red, green, blue and alpha components (treating each as a number, see below)
- length: interpolated as real numbers.
- percentage: interpolated as real numbers.
- integer: interpolated via discrete steps (whole numbers). The interpolation happens in real number space and is converted to an integer using floor().
- number: interpolated as real (floating point) numbers.
- transform list: see CSS Transforms specification: http://www.w3.org/TR/css3-2d-transforms/
- rectangle: interpolated via the x, y, width and height components (treating each as a number).
- visibility: interpolated via a discrete step. The interpolation happens in real number space between 0 and 1, where 1 is “visible” and all other values are “hidden”.
- shadow: interpolated via the color, x, y and blur components (treating them as color and numbers where appropriate). In the case where there are lists of shadows, the shorter list is padded at the end with shadows whose color is transparent and all lengths (x, y, blur) are 0.
- gradient: interpolated via the positions and colors of each stop. They must have the same type (radial or linear) and same number of stops in order to be animated.
- paint server (SVG): interpolation is only supported between: gradient to gradient and color to color. They then work as above.
- space-separated list of above: If the lists have the same number of items, each item in the list is interpolated using the rules above. Otherwise, no interpolation.
- a shorthand property: If all the parts of a shorthand can be animated, then interpolation is performed as if each property was individually specified.
And the following properties must be supported for animations:
- background-color (color)
- background-image (only gradients)
- background-position (percentage and length)
- border-bottom-color (color)
- border-bottom-width (length)
- border-color (color)
- border-left-color (color)
- border-left-width (length)
- border-right-color (color)
- border-right-width (length)
- border-spacing (length)
- border-top-color (color)
- border-top-width (length)
- border-width (length)
- bottom (length and percentage)
- color (color)
- crop (rectangle)
- font-size (length and percentage)
- font-weight (number)
- grid-* (various)
- height (length and percentage)
- left (length and percentage)
- letter-spacing (length)
- line-height (number, length and percentage)
- margin-bottom (length)
- margin-left (length)
- margin-right (length)
- margin-top (length)
- max-height (length and percentage)
- max-width (length and percentage)
- min-height (length and percentage)
- min-width (length and percentage)
- opacity (number)
- outline-color (color)
- outline-offset (integer)
- outline-width (length)
- padding-bottom (length)
- padding-left (length)
- padding-right (length)
- padding-top (length)
- right (length and percentage)
- text-indent (length and percentage)
- text-shadow (shadow)
- top (length and percentage)
- vertical-align (keywords, length and percentage)
- visibility (visibility)
- width (length and percentage)
- word-spacing (length and percentage)
- z-index (integer)
- zoom (number)
The properties of SVG objects are animatable when they are defined as animatable:true in the SVG specification: http://www.w3.org/TR/SVG/struct.html. But at the time where this article is written, I didn’t manage to combine CSS3 Animation directly on SVG elements in any of the latest browsers versions. Today’s samples on the web are then doing a little trick: they are embedding SVG resources into different DIV animated by CSS3 like the I twitty the fool sample.
To declare an animation in a CSS file, here is the kind of generic code you’ll need to write:[crayon-54c669cf5b173340412095/]
Which could also be written like that:[crayon-54c669cf5b19d314258540/]
This animation definition declares 3 steps 0, 50 & 100%. You should at least set a from (or 0%) and a to (or 100%) steps to build a correct animation (minimum 2 steps thus). Once done, you may add as many keyframes as you’d like between 0 and 100% to handle precisely the various steps of your animations.
Once the definition is declared, you can affect it to an element using the classical CSS3 selectors and you’ll need also to configure the animation options. Here the kind of generic blocks you’ll see:[crayon-54c669cf5b1b4887553880/]
To better understand, let’s review a real sample. First of all, as the CSS3 Animations specification is still in a draft stage, you’ll need to use the appropriate vendor prefix. Let’s use IE10 as a sample with the –ms prefix then. Let’s now see how the head of our AT-AT is moving.
Here’s the animation declaration:[crayon-54c669cf5b1c8565549739/]
We’ve got 6 steps (0, 25, 50, 55, 75 & 100%) working on the CSS3 2D transform attributes by changing the value of the rotation.
The animation is then applied via this CSS rule:[crayon-54c669cf5b1db596533878/]
We’re targeting the
element having the “
” and we’re applying the animation named “
rotate-skull” on it. The animation will have to be completed in 7s and be played an infinite number of times.
Here is the living result if your browser supports CSS3 Animations:
We could have written this rule in a shorter manner using the animation shorthand property:[crayon-54c669cf5b1f0766092198/]
The “animation-timing-function” property can be used if you want non-linear animations. You can even mix the type of timing functions during each keyframe.
Basically, CSS3 animations will use cubic bezier curve to smooth the animation by computing different speed over its duration.
The following functions are supported:
- linear: Constant speed
- cubic-bezier: Speed will be computed according to a cubic bezier curve define by two control points : P0 and P1 (so you will have to define 4 values here : P0x, P0y and P1x, P1y.
- ease: Speed will be computed with cubic-bezier(0.25, 0.1, 0.25, 1)
- ease-in: Speed will be computed with cubic-bezier(0.42, 0, 1, 1)
- ease-inout: Speed will be computed with cubic-bezier(0.42, 0, 0.58, 1)
- ease-out: Speed will be computed with cubic-bezier(0, 0, 0.58, 1)
Note: this tool uses in-line SVG supported by Firefox, Chrome, Opera 11.60 & IE9/10. It won’t work properly under Opera 11.50 & Safari on iPad thus.
This is an awesome tool using SVG. You can even play with your mouse on the custom function to edit the curve. If you’d like to know more about this tool, please again have a look to David’s article.
If your browser supports CSS3 animations, let’s now see a simple demo using easing functions to animate a canvas tag containing an animated sprite with CSS3.
Here is the CSS3 animations code that will be used in this demo:[crayon-54c669cf5b20d498064828/]
As well as all the vendor prefixes variations to make sure it works also in Google Chrome & Mozilla Firefox. And here’s the living output:
If your browser doesn’t support CSS3 Animation but support canvas, the sprite’s running animation should be displayed but the character won’t move through the width of the screen.
Note: if you’d like to know more about canvas and sprites animation, you can have a look to this article: HTML5 Gaming: animating sprites in Canvas with EaselJS
The “animation-delay” property simply allows an animation to begin execution some time after it is applied.
3 events could be raised during an animation. They are named “AnimationStart”, “AnimationEnd” and “AnimationIteration”. Depending on your browser, the correct name will be for instance:
- Chrome: webkitAnimationEnd
- Firefox: mozAnimationEnd
- Internet Explorer: MSAnimationEnd
The event will give you the following details:
- animationName: name of the animation which raised the event
- elapsedTime: the amount of time the animation has been running, in seconds
Here is an usage sample for IE10:[crayon-54c669cf5b228200576763/]
More about CSS3 animations
CSS3 animations are really useful for 2 main reasons:
- Hardware acceleration: CSS3 Animations are most of the time directly handled by the GPU and could produce smoother results. This could then be a very interesting approach for mobile devices.
To highlight this importance in performance, the following HTML5 game I wrote using a full frame <canvas>: HTML5 Platformer run at 60 fps in IE9/IE10 on my PC but at 10 fps max on a iPad 2. This is because its CPU is much more limited and the iPad is currently not hardware-accelerating <canvas>. Using CSS3 Transitions/Animations to animate several smaller <canvas> elements could provide a huge performance boost for this game. Think about it when you’re targeting mobile devices!
Since the Platform Preview 3 of IE10 available in the Windows Developer Preview, we’re supporting CSS3 Animations. And as you can see on the following report produced by caniuse.com, the CSS3 animations are now supported on a wide range of browsers:
But as the specification is not finished yet (working draft), you must use vendor’s prefixes such as –ms-, –moz-, –webkit-, –o- to make a cross-browsers compatible application.
But the question could be: how to handle browsers that don’t support this new feature?
First option is to just do nothing. Thanks to the beauty of graceful degradation, you could just let the user only see a static image if you’ve worked correctly. This is for instance the case of these 2 original samples of Anthony: I Twitty the Fool! and Pure CSS3 AT-AT Walker . When watched in IE9, it looks like we only have a static image. When watched in IE10, the very same code shows nice animations. IE10 users will then have an enhanced version while IE9 will still be able to view and use properly the website. The more modern your browser is, the more visual bonus you will have.
I have then written a sample JS library more or less specifically designed for the AT-AT sample.
Animations are nothing more than a series of transitions separated by a certain duration defined via the keyframes. I’ve then reused the concepts built by David Catuhe in his transitions helper library. I let you reviewing his article to check the base of the concepts behind the code.
On my side, I’ve added some support to animate the CSS3 2D Transform rotation & translation values and a way to iterate through the keyframes.
Here is the main part of the library you need to review:[crayon-54c669cf5b24e548147108/]
The first part of the code is iterating through each keyframe to compute the exact duration specified by each percentage. We’re then defining a
function that will dynamically build the next transition to play based on the current index into the keyframes collection. At last, we’ve got a
function that will monitor the current state of the transition applied. Once the transition is finished or dead, it asks for the next transition, push it to the stack of transitions to be played and moves the indexes.
function is called thanks to this code:
At last, we have this kind of code that helps us building the keyframes:[crayon-54c669cf5b28e500008025/]
To highlight its usage, let’s recreate the previous simple CSS3 Animation skull sample with this library :[crayon-54c669cf5b2a1088388599/]
And here is the result that will now work in every browser supporting CSS3 2D Transform:
At last, the very first sample demonstrated at the beginning of this article uses Modernizr to check the support for CSS3 Animations. If it’s not the case, it loads the code that will mimic the keyframes defined in the file master.css, moz-master.css & ms-master.css :[crayon-54c669cf5b2b8973126927/]
You now have an idea on the way to build a fallback mechanism to support more browsers while starting to use the latest CSS3 specifications.
You can download the files for the main sample here: http://david.blob.core.windows.net/html5/css3atat/CSS3ATATNonMinified.zip
- Article about CSS3 Transitions by David Catuhe: Introduction to CSS3 Transitions
- CSS3 Animations specifications: http://www.w3.org/TR/css3-animations/
- IE Test Drive on CSS3 animations: http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_animations.htm
Other useful posts: