Javascript animation and motion equations
View all blog entries Published | 16.08, 8th of August 2008
Recently, I've been looking at the way I can improve and optimise my javascript animations.
A good example would be the 'Apply for job' scroll down on http://www.dnarecruit.com/jobdetails/3180 - clicking the apply for job scrolls a hidden form into view - the scroll is a continuous motion with no acceleration, no deceleration, not even a time parameter. I simply increment the height of the element until it reaches its DOM scrollHeight property.
I've always wanted to script a smooth accelerate/decelerate toggle function, so in a little bit of free time I got to work. I started by reading the research of one Scott Schiller, who's javascript animation tutorial raises some very interesting points on CPU-usage and the most efficient methods for animation looping.
I decided to use the setInterval method with a 25 millisecond time parameter, essentially creating a framerate of 40 frames per second for the animation.
For the motion, I used the trigonometric function Math.sin(x) between -90 and 90 degrees, which gives a smooth trough to peak curve - I extracted the y value, and manipulated it to be within a set range, instead of -1 and 1. (I set the range from 0 to 200 in my example). I then applied this value to an objects style.top attribute.
Perhaps best to view the example, the red box is following the sine curve, the blue box is following the cosine curve, and out of curiousity - I've set the green box to follow the tan curve.
I see quite a lot of potential in this - smooth colour fades, toggle scripts, bounce effects - I even decided to have a play with gravity effects using Math.exp(-x) (example) - bit this needs a bit more attention I feel.
Sure wish I could remember more of my A level maths...
Comments
Replied | Jay Vincent - 15.57, 29th of August 2008
http://emailmarketing.artlinesdev.co.uk
The first use of this stuff - click about on the links and watch the scroll motion of the content.