User Tools

Site Tools



Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm

Martin Christen

View Martin Christen's profile on LinkedIn


Timeline of @MartinChristen

MartinChristen avatar

RT @TFConsult: Celebrating 100th birthday of #physicist #RichardFeynman: The marvellous #Feynman lectures on #physics:
About 1 week, 4 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @sergerey: Had a fantastic time giving our workshop on Spatial Data Science with PyData at @GeoPythonConf with @levijohnwolf. Looking f…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @fridex: Everything has an end even such an excellent conference #GeoPythonConf in Basel. Thanks to organizers for such an outstanding c…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

WebGL Tutorial 4: Animation - using requestAnimationFrame

When running an a graphics application at 60 frames per second (FPS) a frame must be drawn within 16.67ms.

Quick redrawing frames is a key element of all 3d graphics engines. Using time events (for example setInterval) has many disadvantages, especially it is not synchronized with other animations (for example CSS, SVG, …) and it is not precise enough.

Luckily there is an API for this, the “requestAnimationFrame”, an example call is:

function renderloop(){

The big drawback of requestAnimationFrame: It is still vendor specific and doesn't run with all WebGL capable browsers.

“requestAnimationFrame” is available in:

  • Chrome Version 24+
  • Firefox Version 23+
  • Internet Explorer 10+
  • Opera 10+
  • (Safari: nightly builds only)

The following code created by Eric Möller, Paul Irish and Tino Zijdel is a cross browser solution with a fallback for all browsers:

(function() {
   var lastTime = 0;
   var vendors = ['ms', 'moz', 'webkit', 'o'];
   for(var x = 0; x < vendors.length &&  !window.requestAnimationFrame; ++x){
      window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
      window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] 
                          || window[vendors[x]+'CancelRequestAnimationFrame'];
   if (!window.requestAnimationFrame)
       window.requestAnimationFrame = function(callback, element) {
           var currTime = new Date().getTime();
           var timeToCall = Math.max(0, 16 - (currTime - lastTime));
           var id = window.setTimeout(function() { 
                    callback(currTime + timeToCall); },timeToCall);
           lastTime = currTime + timeToCall;
           return id;
   if (!window.cancelAnimationFrame)
      window.cancelAnimationFrame = function(id) {

Paul Irish, 2011, "requestAnimationFrame for Smart Animating"
Erik Möller, 2011, requestAnimationFrame for smart(er) animating
Source Code:
Mozilla docs: requestAnimationFrame API

webgl/tutorial04.txt · Last modified: 2013/09/03 15:32 by mchristen