Animation with Continuations
Written by on January 12th, 2007 in Ajax News.
Kris Zyp has written an article discussing the demonstration using continuations in JavaScript to facilitate writing animations with straightforward linear code.
The example is a bunch of bouncing gears that animate up and down as they bounce.
Explanation
When you click on the button, this calls the addGear function and starts a new “thread” of execution. This execution then carries out the steps of the animation in a natural linear coding sequence.
The Narrative JavaScript framework creates the ability to have multiple threads. Each time you click the button, you are effectively creating a new thread of execution. Of course the underlying JS VM is single threaded, but cooperative multithreading is possible as threads suspend execution through the continuation system.
JAVASCRIPT:
function addGear() { var self = this; function makeGear() { // create the DOM img element for the gear var gear = document.createElement(”img”); gear.src=”images/Configurator.gif”; gear.style.position=”absolute”; self.gearArea.appendChild(gear); return gear; } function bounceGear(gear, positionX, velocityY) { // do a single bounce var y = 0; gear.style.left = positionX + “px”; do { velocityY = velocityY - 0.4; // make a parabolic bounce y += velocityY; gear.style.bottom = y + “px”; sleep(20); // pause for 20 milliseconds } while (y> 0); } function waitForClick(gear) { var notifier = gear.onclick = new EventNotifier(); notifier.wait(); // pause until the click happens gear.onclick = null; } function doBouncingGear() { // this carries out the overall animation var gear = makeGear(); // create the gear element var x = Math.random() * 400; // random x position var bounceVelocity = 15; do { // do a decaying bounce bounceGear(gear,x,bounceVelocity); // do one bounce bounceVelocity = bounceVelocity/1.3; // the bounce/velocity decreases each time } while (bounceVelocity> 1) // gotta stop sometime // finished bouncing waitForClick(gear); // wait for the user to click on it // next in the sequence is to roll it away var velocityX = 0; do { // now we will roll it away velocityX += 0.2; x += velocityX; gear.style.left = x + “px”; sleep(30); } while (x <400); // now we will remove it gear.parentNode.removeChild(gear); } doBouncingGear(); // execute the animation }
Source: Ajaxian
Original Article: http://ajaxian.com/archives/animation-with-continuations
