20

How do I drive an animation loop or game loop at 60fps in a Dart web application?

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279

1 Answers1

34

Use window.animationFrame, the Future-based cousin of the traditional window.requestAnimationFrame.

Dart has been shifting to use Future and Stream as more object-oriented ways to handle asynchronous operations. The callback-based (old 'n busted) requestAnimationFrame is replaced by the Future-based (new hotness) animationFrame.

Here is a sample:

import 'dart:html';

gameLoop(num delta) {
  // do stuff
  window.animationFrame.then(gameLoop);
}

void main() {
  window.animationFrame.then(gameLoop);
}

The signature of animationFrame looks like:

Future<num> animationFrame();

Notice how animationFrame returns a Future that completes with a num, which holds a "high performance timer" similar to window.performance.now(). The num is a monotonically increasing delta between now and when the page started. It has microsecond resolution.

The Future completes right before the browser is about the draw the page. Update the state of your world and draw everything when this Future completes.

You must request a new Future from animationFrame on every frame, if you want the animation or loop to continue. In this example, gameLoop() registers to be notified on the next animation frame.

BTW there is a pub package named game_loop, which you might find useful.

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
  • That game_loop link gives a 404 – Tgwizman Jan 29 '14 at 05:41
  • 1
    How is requestAnimationFrame old 'n busted? Looking at the source the Future based animationFrame creates a completer to be that is triggered by using the original (old 'n busted) requestAnimationFrame callback? – paulecoyote Jul 07 '14 at 22:26
  • 1
    @paulecoyote I don't believe Seth meant requestAnimationFrame is old 'n busted; but rather the idea of using callbacks; Futures are a much nicer API. – Danny Tuppeny Sep 28 '14 at 18:28