如何通过requestAnimationFrame传递参数?

Tor*_*iks 19 javascript requestanimationframe

在主程序中,我随机选择一个我想要动画的对象,所以我用对象作为参数调用该函数.第一个循环没问题,X设置得很好,但是在下一个循环中它变得不确定.

像这样的东西:

var anim = {
        mainFunc: function(x) {
            anim.update(x);
            anim.redraw(x);
            window.requestAnimationFrame(anim.mainFunc);
        },

        update: function(x) {

        },

        redraw: function(x) {

        }
};

var n=Math.floor(Math.random() * (ArrayOfAnimObject.length));
anim.mainFunc(ArrayOfAnimObject[n]);
Run Code Online (Sandbox Code Playgroud)

kal*_*ley 40

您需要创建一个引用或将函数调用包装在另一个函数中,如下所示:

mainFunc: function(x) {
    anim.update(x);
    anim.redraw(x);
    window.requestAnimationFrame(function() {
        anim.mainFunc(x);
    });
}
Run Code Online (Sandbox Code Playgroud)


吖奇说*_*HUō 18

你也可以使用.bind.

mainFunc: function(x) {
    anim.update(x);
    anim.redraw(x);
    window.requestAnimationFrame(anim.mainFunc.bind(anim,x));
}
Run Code Online (Sandbox Code Playgroud)


Kai*_*ido 6

最好的办法可能是避免不得不这样做。

允许您执行此操作的解决方案将要求您在每一帧创建一个新的 Function(无论是来自@kalley 的答案的匿名包装器,还是来自@ArchyWillHe 的绑定的)。

在动画循环中,您希望尽可能保留可收集性较低的对象,这样垃圾收集器就不必在动画运行时启动,在它发生时杀死几帧。

为了执行此操作,您有不同的策略可用,但例如在 OP 中公开的情况下,此x参数可能应该anim直接附加到对象:

var anim = {
  mainFunc: function() {
    anim.update();
    anim.redraw();
    window.requestAnimationFrame(this.mainFunc);
  },

  update: function() {
    this.x ++;
  },

  redraw: function() {
    log.textContent = this.x;
  }
};
// replace it with a bound function only once
anim.mainFunc = anim.mainFunc.bind(anim);
anim.x = 0; // attach the parameter to the anim object
anim.mainFunc();
Run Code Online (Sandbox Code Playgroud)
<pre id="log"></pre>
Run Code Online (Sandbox Code Playgroud)

人们也可能更喜欢只将此参数保留为调用者和 可用的变量anim

(function() {

var anim = {
  mainFunc: function() {
    anim.update();
    anim.redraw();
    window.requestAnimationFrame(anim.mainFunc);
  },

  update: function() {
    x ++;
  },

  redraw: function() {
    log.textContent = x;
  }
};
var x = 0; // available for both us and anim's method
anim.mainFunc();

})();
Run Code Online (Sandbox Code Playgroud)
<pre id="log"></pre>
Run Code Online (Sandbox Code Playgroud)