requestAnimationFrame method

Expand
0 out of 6 rated this helpful - Rate this topic

requestAnimationFrame method

[This documentation is preliminary and is subject to change.]

Registers a function to be called when the system is ready to update (repaint) the display. This provides smooth animations and optimal power efficiency by allowing the system to determine when this occurs. The visibility of the web application and the display refresh rate are used to determine the appropriate speed of the animations, e.g. the number of frames per second supported by the system.

Syntax

var retVal = window.requestAnimationFrame(callback);

Standards information

Parameters

callback [in]

Type: Function

Return value

Type: Integer

A handle to the animationFrame request.

Remarks

Because requestAnimationFrame takes the visibility of the web application and the refresh rate of the display into account, animation occurs when the system is ready. This leads to smoother animations and less power consumption than animations accomplished using older techniques, such as those based on the setTimeout and setInterval methods.

The requestAnimationFrame method creates only a single animation request. To create an animation, register new requests for each frame of the animation, as shown in the following example.

To cancel an animation request, use cancelAnimationFrame.

Examples

The following example shows three functions that demonstrate how to use requestAnimationFrame to create an animation.


<!DOCTYPE html>
<title>Script-based animation using requestAnimationFrame</title>
<style>
div { position: absolute; left: 10px; padding: 50px;
  background: crimson; color: white }
</style>
<script>
var requestId = 0;

function animate(time) {
  document.getElementById("animated").style.left =
    (animationStartTime % 2000) / 4 + "px";
  requestId = window.requestAnimationFrame(animate);
}
function start() {
  animationStartTime = Date.now();
  requestId = window.requestAnimationFrame(animate);
}
function stop() {
  if (requestId)
    window.cancelAnimationFrame(requestId);
  requestId = 0;
}
</script>
<button onclick="start()">Click me to start!</button>
<button onclick="stop()">Click me to stop!</button>
<div id="animated">Hello there.</div>

See also

window
cancelAnimationFrame
animationStartTime

 

 

Build date: 5/22/2012

Did you find this helpful?
(1500 characters remaining)
Community Additions ADD