Monday, June 6, 2011

A basic look at dojo.Animation


Recently, I needed to animate rotation of an HTML button.  I use the Dojo javascript library, which has some frameworks for animation. Unfortunately, the core framework, dojo.Animation isn't well documented. For example, if you look at:
http://dojotoolkit.org/reference-guide/quickstart/Animation.html
The documentation and examples are written in terms of higher-level APIs. It turns out that the base animation API is quite simple. Basically, all you need to do, at a minimum, is specify starting and ending values and set up some event handlers. Here's some example code to rotate a node:

new dojo.Animation({
    curve: [0, 360],
    onAnimate: function (v) {
        node.style[transform] = 'rotate(' + v + 'deg)';
    }
}).play();

In the example, I used a variable, transform for the style name. This is necessary because different browsers use different names for the style property that provides for rotation. A full working example can be found at
http://jimfulton.info/demos/dojo-animated-rotate.html
There are various additional properties you can provide to the Animation constructor to control things like duration, frame rate and repeats. You can also provide handlers for beginning, and end of animation. The later is especially important because animation is asynchronous and you often want to perform some action when an animation is done. The API documentation covers these pretty well:
http://dojotoolkit.org/api/1.6/dojo/Animation
The dojo helper functions provide some convenience. For example, to fade a node in:

dojo.fadeIn({node: node})

which is simpler than:

new dojo.Animation({
    curve: [0, 1],
    onAnimate: function (v) { node.style.opacity = v; }
}).play()

but it's nice to know that fadeIn is just a short hand for some pretty simple code.

This is a good example of a low-level API that provides a lot of value, but that gets obscured by higher-level APIs that provide convenience in common cases. 

1 comment:

  1. please post same logic in dojo 1.7 it will be helpful for me and other users

    ReplyDelete