所以我正在尝试创建一个'Animator‘模块,它基本上使得启动和停止requestAnimationFrame循环变得容易
define(function(require, exports, module) {
var a = require( 'js/lib/stats.min.js' );
function Animator(){
this.stats = new Stats();
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.bottom = '0px';
this.stats.domElement.style.right = '0px';
this.stats.domElement.style.zIndex = '999';
this.requestAnimationFrame = requestAnimationFrame;
document.body.appendChild( this.stats.domElement );
}
Animator.prototype.start = function(){
this.animate( this );
}
Animator.prototype.stop = function(){
if (requestId) {
cancelAnimationFrame(this.requestId);
this.requestId = undefined;
}
}
Animator.prototype.animate = function( ){
this.update();
this.requestId = this.requestAnimationFrame( this.animate );
}
// Empty function, because it will be user defined
Animator.prototype.update = function(){
}
return Animator
});如你所知,我在这里做了一些非法的事情:
首先,我尝试将requestAnimationFrame赋值给this.requestAnimationFrame。这是因为在原型的.animate函数上,我希望能够访问此对象的更新函数。问题是,当我这样做时,就像这样:
Animator.prototype.animate = function( ){
whichAnimator.update();
whichAnimator.requestId = requestAnimationFrame( whichAnimator.animate( whichAnimator ) );
}我得到的堆栈调用超过了最大值。
我想我想知道最好的方法是什么,因为在这一点上我显然不知道我在做什么。
如果您有任何问题,请提问,并提前感谢您的时间!
发布于 2013-10-20 05:33:30
.bind做到了!
谢谢@kalley
Animator.prototype.start = function(){
this.running = true;
this.animate();
}
Animator.prototype.stop = function(){
this.running = false;
}
Animator.prototype.animate = function( ){
this.stats.update();
this.update();
if( this.running == true ){
window.requestAnimationFrame( this.animate.bind( this ) );
}
}发布于 2013-10-20 05:35:17
requestAnimationFrame不像setInterval那样工作,每个调用的requestID都是不同的。因此,将其分配给上下文实际上是没有意义的。
我发现如果你只是在全局运行一个requestAnimationFrame,然后调用你在循环中运行的任何动画,那么你会更容易喘息。下面是一些粗略的代码:
var animations = {}; // holder for animation functions
(function loop() {
for(var id in animations) {
animations[id]();
}
requestAnimationFrame(loop);
}());
function start(fn) {
var id = +new Date();
animations[id] = fn;
return id;
}
function stop(id) {
if (animations.hasOwnProperty(id)) {
delete animations[id];
}
}https://stackoverflow.com/questions/19471247
复制相似问题