Search

8/23/2009

javascrip animation

Javascript Animation: Tutorial, Part 1 - Schillmania.com
Javascript Animation: Tutorial, Part 2 - Schillmania.com

From my experience and findings over the years, the primary source of CPU drain stems from the browser's reflow/redaw response to dynamic changes in the DOM.

var points = {
// moving a box "from" and "to", eg. on the X coordinate
'from': 200,
'to': 300
}
var frameCount = 20; // move from X to Y over 20 frames
var frames = []; // array of coordinates we'll compute

// "dumb" tween: "move X pixels every frame"
var tweenAmount = (points.to - points.from)/frameCount;
for (var i=0; i<frameCount; i++) {
// calculate the points to animate
frames[i] = points.from+(tweenAmount*i);
}
// frames[] now looks like [205,210,215,220, ... ,300]; etc.

A more realistic tweening effect (including acceleration and deceleration) is achieved by changing the amount of motion made with each frame.

var points = {
// moving a box "from" and "to", eg. on the X coordinate
'from': 200,
'to': 300
}
var animDelta = (points.to - points.from); // how far to move

// animation curve: "sum of numbers" (=100%), slow-fast-slow
var tweenAmount = [1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1];
// move from X to Y over frames as defined by tween curve
var frameCount = tweenAmount.length;
var frames = []; // array of coordinates we'll compute
var newFrame = points.from; // starting coordinate
for (var i=0; i<frameCount; i++) {
// calculate the points to animate
newFrame += (animDelta*tweenAmount[i]/100);
frames[i] = newFrame;
}
// frames[] now looks like [201,203,206, ... ,228,236,245, ... ,297,299,300]; etc.

A linear acceleration and deceleration motion as above produces a visual improvement over a straight, linear motion. Each loop iteration adds a percentage of the total distance to move according to the tween amount, which adds up to 100%. Full-featured Javascript animation libraries go far beyond this in using bezier curves and fancier math functions, which provide much smoother motion tweens.

Javascript Animation: Tutorial, Part 3
demo: http://www.schillmania.com/content/projects/javascript-animation-2/demo/
Bernie's Better Animation Class , animator.js

沒有留言: