javascript 如何使用 requestAnimationFrame 传递参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19893336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pass argument with requestAnimationFrame?
提问by Torfiks
In the main program I randomly choose an object which I'd like to animate, so I call the function with the object as the argument. The first loop is okay, x
is finely set, but in the next turn it becomes undefined
.
在主程序中,我随机选择了一个我想要制作动画的对象,因此我以该对象作为参数调用该函数。第一个循环没问题,x
设置得很好,但在下一回合它变成了undefined
。
Something like this:
像这样的东西:
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]);
回答by kalley
You either need to create a reference or wrap the function call in another function like so:
您需要创建引用或将函数调用包装在另一个函数中,如下所示:
mainFunc: function(x) {
anim.update(x);
anim.redraw(x);
window.requestAnimationFrame(function() {
anim.mainFunc(x);
});
}
回答by u2041954
回答by Kaiido
The best is probably to avoid having to do it.
最好的办法可能是避免不得不这样做。
The solutions that would allow you to do this will require that you create a new Function (be it the anonymous wrapper from @kalley's answer, or the bound one from @ArchyWillHe's) every frame.
允许您执行此操作的解决方案将要求您在每一帧创建一个新的 Function(无论是来自@kalley 的答案的匿名包装器,还是来自@ArchyWillHe 的绑定的)。
In an animation loop, you want to leave the less collectable objects as possible, so that the Garbage Collector doesn't have to kick in while your animation is running, killing a few frames when it will happen.
在动画循环中,您希望尽可能保留可收集性较低的对象,以便垃圾收集器在您的动画运行时不必启动,在它发生时杀死几帧。
In order to perform this, you have different strategies available, but for instance in the case exposed in OP, this x
parameter should probably be attached to the anim
object directly:
为了执行此操作,您有不同的策略可用,但例如在 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();
<pre id="log"></pre>
One may also prefer just keeping this parameter as a variable available for both the caller and anim
:
人们也可能更喜欢只将此参数保留为调用者和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();
})();
<pre id="log"></pre>