Each line is drawn when the system is ready to draw it through the use of requestAnimationFrame. The requestAnimationFrame method accepts a function to be called at the next chance to display a frame. Unlike the setTimeout method which tries to execute the function on a set interval, requestAnimationFrame doesn’t waste cycles trying to update the screen when the system isn’t ready.
To stop the animation, the cancelAnimationFrame method is called, which blocks the currently pending requestAnimationFrame call. You can click Clear to clear the canvas and start again.
Because requestAnimationFrame and cancelAnimationFrame are not yet standards, some browser vendors are using prefixed versions of the API. This sample uses an alias, and substitutes the version of the API that works. If none of them work, setTimeout is used.
// Request another time slot to do this all over again handle = requestAFrame(drawStick); // handle multiple browsers for requestAnimationFrame() window.requestAFrame = (function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || // if all else fails, use setTimeout function (id) { return window.setTimeout(id, 16.67); // shoot for 60 fps }; })();
requestAnimationFrame method
cancelAnimationFrame method
Canvas and 2dContext
The requestAnimationFrame Method on the Internet Explorer 10 Developers guide Sampling image colors with Canvas (good color info reference)
Under the Hood: Bubbles Using PC Hardware more efficiently in HTML5: New Web Performance APIs, Part 1
Using requestAnimationFrame for power efficient animations sample