Animator.js: JavaScript animation library

Animator.js was a library I wrote back in 2006 to handle animation on web pages. For a time it was quite ahead of the curve: It was the first library to feature CSS morphing - the ability to smoothly transition between two styles defined as CSS classes.

The world of JavaScript has moved on a lot since then. Animator.js has now been incorporated into most of the major JavaScript frameworks, either by directly porting the code (Animator.js is released under a BSD license that allows people to do this) or by borrowing the techniques. Animator.js has served its purpose, and most people will be better served by a general purpose JavaScript framework: I recommend jQuery.

I'm keeping this page up here for historical interest, and because Animator.js may still be of interest to people who want a small, fast library that does animation and nothing else.

Thanks to Tim Stone, Kaspar Fischer, Clint Priest and other developers who contributed feedback and features.

Background and motivation

I've removed this section because it contained criticisms of other JavaScript libraries that were true in 2006, but not today. I also took the opportunity to rant on the topic of object-oriented inheritance, which was a topic I explored in greater length in the article Inheritance is Evil and Must Be Destroyed - Bernie Sumption, 2010

A better way of animating

An Animator is an object that generates a series of numbers between zero and one. Zero represents the start of the animation, one the end.

Check this out:

// This object controls the progress of the animation
ex1 = new Animator()
// the Animator's subjects define its behaviour
ex1.addSubject(updateButton);
function updateButton(value) {
    var button = document.getElementById("ex1Button");
    button.innerHTML = "Progress: " + Math.round(value * 100) + "%";
}
// now click below: each click to the button calls ex1.toggle()

The Animator above was left with the default options, here's an example that uses more configuration:

ex2 = new Animator({
    duration: 1200,
    interval: 400,
    onComplete: function() {
        document.getElementById("ex2Target").innerHTML += "Bing! ";
    }
})
ex2.addSubject(updateButton);
function updateButton(value) {
    document.getElementById("ex2Target").innerHTML += " Badda ";
}

Animating element styles

Most of the time you want to animate one or more a style properties of an element. There are essentially only three kinds of CSS value - ones that scale numerically (like 10px), ones that scale with a RGB colour value(like #RRGGBB), and ones that don't scale (like bold / italic). Animator provides three utility classes for each of these kinds of properties, and between them they can animate any CSS style.

// animate margin-left from 0 to 100 px
ex3 = new Animator().addSubject(
    new NumericalStyleSubject(
        "ex3Button",
        "margin-left",
        0,
        100));

// animate background-color from white to black
ex4 = new Animator().addSubject(
    new ColorStyleSubject(
        "ex4Button",
        "background-color",
        "#FFFFFF",
        "#F4C"));

// animating both - note how calls to addSubject() can be chained:
ex5 = new Animator()
    .addSubject(
        new NumericalStyleSubject(
            "ex5Button",
            "margin-left",
            0,
            100))
    .addSubject(
        new ColorStyleSubject(
            "ex5Button",
            "background-color",
            "#FFFFFF",
            "#F4C"))
    .addSubject(
        new DiscreteStyleSubject(
            "ex5Button", "font-weight",
            "normal",
            "bold",
            0.5));
// also, check out the last subject, which causes font-weight to
//switch from normal to bold half way through the animation

If you've ever used moofx or scriptaculous then you are probably thinking that this is quite verbose, and you'd be right. Animator has a killer feature that removes the verbosity, but before we get to that, here are a couple more things you can do:

More complex effects

What if you have a number of elements that you want to animate in the same way? In that case, pass an array of elements into the Subject's constructor. There is no way to add and remove elements from a Subject after it has been constructed - if you want to do that, use one Subject for each element and use addSubject() and removeSubject() on the Animator.

// Applying the same effect to different elements is easy
ex6 = new Animator().addSubject(
    new NumericalStyleSubject(
        ["dot1", "dot2", "dot3"],
        "margin-right",
        10,
        50));
     

In previous examples, each subject has referred to the same element. This does not have to be the case:

// applying different effects to different elements is possible
ex7 = new Animator()
    .addSubject(
        new ColorStyleSubject(
            "ex5ButtonA",
            "background-color",
            "#FF9",
            "#9F9"))
    .addSubject(
        new NumericalStyleSubject(
            "ex5ButtonB",
            "padding",
            "5px",
            "15px"));

   

Opacity gets special treatment. Since IE does not support the standard 'opacity' CSS style, NumericalStyleSubject will convert it into an appropriate filter.

ex8 = new Animator().addSubject(
    new NumericalStyleSubject(
        "ex8Button",
        "opacity",
        1,
        0.25));

Controlling the animation

When you click on a sample button in this article, you are calling toggle() on an animator object. There are a few more control functions:

  • play() plays the animation from the start to the end
  • stop() stops the animation at its current position
  • reverse() plays the animation in reverse
  • seekTo(pos) plays the animation from it's current position
  • seekFromTo(from, to)
play()
0%
stop()
reverse()
seekTo(0.5)
seekFromTo(0.25, 0.75)

The benefit of using seekTo() is that it wil avoid sudden jumps in state when called half way through an animation:

this div uses play() and reverse on mouseover and mouseout
this div uses seekTo(1) and seekTo(0) on mouseover and mouseout

Transitions

A transition is a function that takes a state (a number between 0 and 1) and returns another number between 0 and 1. This can be used to simulate acceleration, deceleration and more complex effects. You can pass in a transition to an Animator object's constructor using the cleverly named transition property.

The Animator.tx object provides a few ready made transitions:
  • Animator.tx.easeInOut is the default transition, and creates a smooth effect
  • Animator.tx.linear maintains a constant rate of animation
  • Animator.tx.easeIn starts slow, gets faster
  • Animator.tx.strongEaseIn exaggerated version of the above
  • Animator.tx.easeOut starts fast, gets slower
  • Animator.tx.strongEaseOut exaggerated version of the above
  • Animator.tx.elastic go slightly past the target point, then be drawn back
  • Animator.tx.veryElastic as above, but with an extra pass
  • Animator.tx.bouncy Hit the target point then bounce back
  • Animator.tx.veryBouncy as above, but with an extra 2 bounces

Sometimes you'll want to fine tune the above transitions. If you look at the source code where the Animator.tx object is created, you'll see that the above functions are all made by four factory functions:

Animator.makeEaseIn()

// make a transition that gradually accelerates. pass in 1 for smooth
// gravitational acceleration, higher values for an exaggerated effect
ex9 = new Animator({
    transition: Animator.makeEaseIn(3),
    duration: 1000
});
ex9.addSubject(
    new NumericalStyleSubject(
        "ex9Button",
        "margin-left",
        0,
        200));

Animator.makeElastic()

// make a transition that, like an object with momentum being
// attracted to a target point, goes past the target then returns
ex10 = new Animator({
    transition: Animator.makeElastic(3),
    duration: 2000
});
ex10.addSubject(
    new NumericalStyleSubject(
        "ex10Button",
        "margin-left",
        0,
        200));

Animator.makeBounce()

// make a transition that, like a ball falling to floor, reaches
// the target and bounces back again
ex11 = new Animator({
    transition: Animator.makeBounce(3),
    duration: 2000
});
ex11.addSubject(
    new NumericalStyleSubject(
        "ex11Button",
        "margin-left",
        0,
        200));

Animator.makeADSR()

An Attack Decay Sustain Release envelope is a technique I lifted from music production. It is very useful for animations that start and end at the same value.

// This example shows you what an ADSR envelope looks like, but is
// otherwise useless the first three arguments are the boundary
// points of the 4 phases. The last is the sustain level.
// All should be between 0 and 1.
ex12 = new Animator({
    transition: Animator.makeADSR(0.25, 0.5, 0.75, 0.5),
    duration: 2000
});
ex12.addSubject(
    new NumericalStyleSubject(
        "ex12Button",
        'margin-left',
        0,
        400));

A practical use of ADSR is to hold an animation in a certain state for a while, as in this yellow fade example

// This yellow fade is emphasised by holding it at full yellow
// for the first half of the animation
ex13= new Animator({
    transition: Animator.makeADSR(0, 0, 0.5, 1),
    duration: 1500
});
ex13.addSubject(
    new ColorStyleSubject(
        "ex13Button",
        "background-color",
        "#FFFFFF",
        "#FFFF00"));

Custom functions

Of course, you can write your own functions that do any kind of transition:

function setupEx14() {
    var wobbles = parseInt(prompt(
        "Enter a number of wobbles (try between 1 and 5)", ""));
    if (!wobbles) {
        alert("Sorry, I didn't understand that, have 2 wobbles.");
        wobbles = 2;
    }
    // do some kind of crazy trigonometric stuff. I don't even
    // know what it all means, I just went crazy with the Math
    // functions
    ex14Tx = function(pos) {
        return ((-Math.cos(pos*Math.PI*((1+(2*wobbles))*pos))/2) + 0.5);
    }
    ex14 = new Animator({
        transition: ex14Tx,
        duration: 2000
    });
    ex14.addSubject(
        new NumericalStyleSubject(
            "ex14Button",
            "margin-left",
            0,
            100));
    ex14.play();
};

 

The killer feature

I wanted to explain how Animator works under the hood before I revealed this feature.

Like I said before, it's all a bit verbose at the moment, and most of the code in the above examples is just boilerplate. What we need is some kind of language that lets us define the style that we want to animate an object towards. Oh wait a second, we've already got one: CSS. A CSS style contains all the information we need to define an animation state:

ex15 = new Animator().addSubject(
    new CSSStyleSubject(
        "ex15Button",
        "width: 10em; background-color: rgb(256, 256, 256); font-style: normal",
        "width: 40em; background-color: #F39; font-style: italic"));
// note how you can use any unit, not just 'px'.

CSSStyleSubject is a wrapper around the other three Subjects. It parses two CSS rule sets and for each property declaration, creates a NumericalStyleSubject if it looks like a number, or a ColorStyleSubject if it looks like a colour, or a DiscreteStyleSubject otherwise. DiscreteStyleSubjects are created with a threshold of 0.5, in other words the style changes from normal to italic half way through the animation.

Conveniently, you can also pass in CSS class names instead of rule sets:

ex16 = new Animator().addSubject(new CSSStyleSubject(
    "ex16Button",
    "small white",
    "big blue bendy"));
// the classes small, big, white, blue and bendy are
// defined in this page's source.

When you're creating animations from CSS classes, it's easy to lose track of what your animator object is doing. The Animator.inspect() method returns a string that describes the animator:

This is pretty good, but we can still remove some more cruft. Most of the time, the element you want to animate will already be in its initial style. If this is the case, you can omit one of the rule sets and the initial state will be inferred from the elements current style. This uses getComputedStyle (or Element.currentStyle in IE) so reflects the element's actual style after applying CSS rules in style sheets.

ex17 = new Animator().addSubject(
    new CSSStyleSubject(
        "ex17Button",
        "width: 300px; background-color: #F39"));

Finally, there is one last bit of syntactic sugar to make it easy to apply effects. The Animator.apply(element, style, options) function is a wrapper around creating a single CSSStyleSubject. The second argument is the style to fade to and the third is an optional set of constructor parameters for the Animator object. If you want to specify the full from and to styles, pass in a two item array as the second parameter.

ex18 = Animator.apply("ex18Button", "greenish"); // ta da!

Oh go on, one more feature...

By popular demand... Several people asked for an easy way to chain several animations together. AnimatorChain is an object that behaves a bit like an Animator, but wraps several other Animator objects and causes them to play in sequence.

var animators = [];
for (var i=0; i<3; i++) {
    animators[i] = Animator.apply("ex18blob-" + i), "blobEnd";
}
ex19 = new AnimatorChain(animators);
// the AnimatorChain object has toggle(), play(), reverse()
// and seekTo(state) functions just like Animator objects,
// so you can often use them where code expects an Animator

Well, that's it. Enjoy using Animator.js, and feel free to leave comments and feedback below.

150 Responses to Animator.js: JavaScript animation library

  1. aswani says:

    thanks for this awesome library. im happy to see soundmanager using this great library. thank you once again for sharing it.

  2. Pingback: Motion paths with Canvas | Journal – Mark Brown

  3. ten says:

    rgb(256, 256, 256)?
    256? 255?

    • bernie says:

      255. It’s an 8 bit unsigned integer, so values above 255 are invalid. If you’re lucky, the program interpreting the number will round it down. Otherwise it might overflow to 0, or do something else wacky.

  4. Remi says:

    Awesome library, I discovered it late (with soundmanager), I will use it!!!!!

  5. Mojtaba says:

    Thank you for your nice library, thanks for sharing and details.
    Very usefull article. I’m following u.

  6. Doodler says:

    I like it very much. If it is incorporated into the jQuery.animator I have not figured out yet how.

  7. Canyon says:

    I took a look. Not bloated, simple, efficace, nice. Like it. Thanks.

  8. James says:

    A very underrated piece of kit, Bernie.

    James

  9. moses says:

    I am convinced that this really great although I am just but a very new learner of js

  10. Wes says:

    hi Bernie, I think that the opacity part must be fixed in some way, because I always have problems with IE (ie9 accepts opacity and -ms-opacity also)

    the fix would be setting always every “synonym” of “opacity” independently by the browser

    • bernie says:

      I’m not really maintaining Animator any more, and I’m recommending jQuery as an alternative. If you fix this, send me a patch and I’ll update the distribution.

      • Wes says:

        jquery sucks!

        your Animator’s OOP design is excellent, and I will continue to use it for this reason…

        btw I will fix this, someday, and I will update you

        thank you :)

  11. Hey Bernie,

    Have you seen the Greensock animation framework?

    It is a new animation framework that performs above and beyond everything else currently available (It’s about 10 times faster than jQuery).

    If you’re interested, check out my tutorial: Greensock JavaScript Animation.

  12. Pia says:

    i love you. <3

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>