JS animation

2009-12-26

After creating the parallax demo I wanted to create an actual animation. But I suck at graphics so I figured I'd use an animation tutorial in flash and copy that to Javascript.

A few hours later, here's the result :) (live demo)

I've used a tutorial at tutsplus.com, but mainly for a flash example to port to javascript. The actual tutorial was useless to me (sorry :)).

I used an swf-decompiler to rip the graphics (he put them in the tutorial but left the drawing lines so I went out of my way to get them slightly different. I needed to create a sprite for the car anyways). Michael, if you object I'll take it down and change the gfx, somehow.

How this works is quite simple. First the images are (pre)loaded. The mountains and road are displayed absolutely inside a container. They have a background image which repeats and are as wide as the viewport (of the animation). The car uses a sprite with five cars to create the wobble effect. It is shrunk and sprited using CDE.sprite. Finally the tree starts offscreen.

The controls are added above the animation and the footer is added below.

Next the animation starts. The animation is a setInterval with 1000/30, 1000/60 and 1000/100 interval. Note that this is rounded so it's not "exactly" that many fps, except perhaps for 100 fps, but no browser gets 100fps at this moment...

During each animation step the actual time is used to check the position of every graphic. A generic formula of ~~((t % (s*w))/s) is applied to determine the position. Here t is the current time in milliseconds and s is the speed of the animation for that specific graphic. Higher is slower. w is the width of the graphic, this is used to make the transition smooth. The result returns a number which can be translated to the offset of the background. I negate that so the effect goes left, not right. Note that ~~ is a short trick for Math.round().

For the car I simply track the last car-id shown (out of five) and only update the car sprite when it changed.

The tree scrolls by every so often and disappears offscreen again.

The results are interesting. I've added a frame counter which you can see at the top of the demo. The browsers I've tested peak as follows (IE requires a refresh, due to some caching technique I rely on):

Safari (4.04): 10 97 fps
IE (8): 17 fps
Firefox (3.5): 78 fps
Opera (10.10): 92 fps
Chrome (3.0): 148 fps

Live demo

I wouldn't have thought Safari would score so badly. All that happens is some background shifting and moving of one element... Maybe something else is going on though. I've had reports that Safari runs at 70fps, max 97. So maybe that's just my configs going bad... :(

Ahwell. I'll have some more fun with animations. I'm sure canvas will aid me. Eventually I wouldn't mind reaching a point like effectgames, who have my respect for creating that framework :)

So, I hope it helps you, somehow... :)