requestAnimationFrame 带有回调函数?

use*_*806 2 javascript

单击按钮后,我会在画布上制作一些动画。动画完成后,我想调用一个函数,该函数作为参数传递到requestAnimationFrame首先初始化的函数中。

这可能吗?

我尝试了各种方法,使用匿名函数等。

var anim = false;
var game = new Game();

function Game(){
  this.turn = 1;

  this.move = function(){
    this.animate(game.advanceTurn);
  }

  this.advanceTurn = function(){
     this.turn++;
  }

  this.animate = function(callback){
    var done = false;
    anim = window.requestAnimationFrame(game.animate);

    // animation code here

    if (done){
        window.cancelAnimationFrame(anim);
        anim = false;
        callback();
    }
  }
Run Code Online (Sandbox Code Playgroud)

即单击按钮,制作动画,动画完成,调用 game.advanceTurn。

当记录提供的参数时,控制台首先会记录我的回调函数,然后将其替换为我认为是计时器测量的内容(符合 MDN 的描述rAF)。

tri*_*cot 5

您可以用来bind让您的回调函数被传递。同时你也可以传递this,这样你就可以保留对当前 Game 对象实例的引用:

function Game(){
  var i = 0;
  var anim = false;
  
  this.turn = 1;

  this.move = function(){
    this.animate(this.advanceTurn.bind(this));
  }

  this.advanceTurn = function(){
     this.turn++;
  }

  this.animate = function(callback){
    var done = false;
    anim = window.requestAnimationFrame(this.animate.bind(this, callback));

    // animation code here
    console.log(i++);

    if (i>5){
        window.cancelAnimationFrame(anim);
        i = 0;
        anim = false;
        callback();
    }
  }
}

new Game().animate(function () {
   console.log('callback received');
});
Run Code Online (Sandbox Code Playgroud)