首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >requestAnimationFrame,非全局?

requestAnimationFrame,非全局?
EN

Stack Overflow用户
提问于 2013-10-20 05:17:10
回答 2查看 795关注 0票数 1

所以我正在尝试创建一个'Animator‘模块,它基本上使得启动和停止requestAnimationFrame循环变得容易

代码语言:javascript
复制
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函数上,我希望能够访问此对象的更新函数。问题是,当我这样做时,就像这样:

代码语言:javascript
复制
Animator.prototype.animate = function( ){

  whichAnimator.update();

  whichAnimator.requestId = requestAnimationFrame( whichAnimator.animate( whichAnimator ) );

}

我得到的堆栈调用超过了最大值。

我想我想知道最好的方法是什么,因为在这一点上我显然不知道我在做什么。

如果您有任何问题,请提问,并提前感谢您的时间!

EN

回答 2

Stack Overflow用户

发布于 2013-10-20 05:33:30

.bind做到了!

谢谢@kalley

代码语言:javascript
复制
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 ) );
  }

}
票数 2
EN

Stack Overflow用户

发布于 2013-10-20 05:35:17

requestAnimationFrame不像setInterval那样工作,每个调用的requestID都是不同的。因此,将其分配给上下文实际上是没有意义的。

我发现如果你只是在全局运行一个requestAnimationFrame,然后调用你在循环中运行的任何动画,那么你会更容易喘息。下面是一些粗略的代码:

代码语言:javascript
复制
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];
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19471247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档