How do I drive an animation loop or game loop at 60fps in a Dart web application?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With