How do I drive an animation loop at 60fps with Dart and the web?

﹥>﹥吖頭↗ 提交于 2019-11-28 21:17:52

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!