CSS animations and Javascript
Usualy, to animate CSS properties with Javascript, you'd use a tweening library to progressively transition their values. But this uses precious UI thread time and CSS3 brings in CSS animations, which run off the UI thread. Performance improvement sounds good, so let's have a look at how they play along with Javascript!
A quick intro to CSS animations
CSS animations are based on keyframes that define the style of the animated element at different stages of the animation. Only animatable properties will be taken into account, though. Not all of them have the same impact on performances when getting animated, though.
You define the set of keyframes for a specific animation using the @keyframes
rule.
You can notice that keyframe position in the animations are defined in percent, not time units.
The actual time of the animation is set on the animated element, along with the set of keyframes
to use (among other properties, using the animation
property.
Triggering an animation
Triggering your animation with Javascript is as simple as setting the appropriate CSS animation
property on your element, using the style
Javascript property, or a class, whichever you prefer. Actually, you can set any of the animation-…
properties this way, which allows you a bit more control on what you set/orverride.
That's already a good deal of control over your animations in Javascript. You can change their duration, play them backwards, pause them… However, if you need to manipulate the keyframes or their content, things get a bit trickier.
Javascript generated keyframes
Sometimes, you'll want to control the intervals between the keyframes at runtime, rather than having them pre-defined in your stylesheet. You might also need to tune the properties inside those keyframes. In this situation, you'll have to generate the keyframes with Javascript before setting the animation
property on the element.
CSSOM provides a handy insertRule
for dynamically adding CSS rules (provided you already have a stylesheet in your page in which to insert the rule, which is often the case). I prefer inserting <style>
tags, which make it easier to remove the animation definition once they're over (CSSOM deleteRule
function works using an index, not ideal if your animations don't finish in the order they started).
In both cases, you'll need to generate a String containing the @keyframes
rule.
Wrapping it up
Javascript provided various ways of interacting with CSS animations. It it pretty simple to tweak the CSS properties configuring the animation on a given element. Despite being a bit trickier, creating custom animations by injecting new sets of keyframe in the page is also possible. Not to mention (well, they were not mentioned in this article actually) the events dispatched by the element when the animation starts, ends or progresses. Generating the keyframes with string templates is still a bit tedious though. Maybe an idea for a nice Javascript library ;)