使用requestanimationframe

时间:2018-01-09 17:49:26

标签: javascript three.js es6-class

我一直在努力创建一个简单的scenemanager类,它也可以处理渲染。

class SceneManager {
    constructor() {

        this.scene = new THREE.Scene();
        this.camera = new THREE.PerspectiveCamera( 60, window.innerWidth/window.innerHeight, 0.1, 10000 );

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setSize( window.innerWidth, window.innerHeight );
    }
    CreateScene(){
        document.body.appendChild( this.renderer.domElement );
        this.scene.add(new THREE.AmbientLight(0x777777));
    }
    RenderCycle(){
        requestAnimationFrame(this.RenderCycle());
        this.renderer.render(this.scene, this.camera);
    }  
}

并调用类似的方法

var sceneManager = new SceneManager();
sceneManager.CreateScene();
sceneManager.RenderCycle();

但是我收到了这个错误:

scenemanager.class.js:18 Uncaught RangeError: Maximum call stack size exceeded
at SceneManager.RenderCycle (scenemanager.class.js:18)
at SceneManager.RenderCycle (scenemanager.class.js:19)
at SceneManager.RenderCycle (scenemanager.class.js:19)
at SceneManager.RenderCycle (scenemanager.class.js:19)
at SceneManager.RenderCycle (scenemanager.class.js:19)

我明白这是因为它会立即调用RenderCycle(),但我不确定如何去做。

感谢任何帮助和指导,谢谢

1 个答案:

答案 0 :(得分:0)

在构造函数中将renderCycle绑定到this类,并使用camelCase(js中的标准):

class SceneManager {

  constructor() {

    this.renderCycle = this.renderCycle.bind(this);

    // ... 
  }

  renderCycle() {

    requestAnimationFrame(this.renderCycle);
    this.renderer.render(this.scene, this.camera);
  }  
}