ThreeJs animate在角度2中失去了上下文

时间:2016-11-30 16:50:39

标签: javascript angular typescript three.js

我想在角度2中使用ThreeJ。我可以获得场景和一个简单的立方体来渲染,但是当使用animate()调用时会出现问题。这是代码。

import { OnInit, Component } from '@angular/core';

const THREE = require('three');

@Component({
  selector: 'app-threejsscene',
  templateUrl: 'threejsscene.component.html'
})
export class ThreeJsSceneComponent implements OnInit {

  scene: THREE.Scene;
  renderer: THREE.Renderer;
  mesh: any;
  camera: THREE.Camera;
  geometry: THREE.Geometry;
  material: THREE.Material;


  ngOnInit() {

    this.scene = new THREE.Scene();

    this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
    this.camera.position.z = 1000;

    this.geometry = new THREE.BoxGeometry( 200, 200, 200 );
    this.material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );

    this.mesh = new THREE.Mesh( this.geometry, this.material );
    this.scene.add( this.mesh );

    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize( window.innerWidth, window.innerHeight );

    document.body.appendChild( this.renderer.domElement );
    this.animate();
  }

  protected animate() {
    requestAnimationFrame( this.animate );

    this.mesh.rotation.x += 1;
    this.mesh.rotation.y += 1;

    this.renderer.render( this.scene, this.camera );

  }
}

因此,当在ngOnInit()内部调用this.animate()时,它会渲染场景(并应用一次旋转)。但是当调用requestAnimationFrame时,我得到“this”未定义的错误。因此,看起来“这个”指的是关于这个类的背景会丢失。

所以我的问题:是否有正确/最好的方法来维护“this”的上下文,还是有其他方式来运行动画循环? 提前谢谢!

2 个答案:

答案 0 :(得分:2)

找出解决方案。可能不是最干净的,如果有人有更好的答案,将改变答案。我在一个字段中添加了一个调用animateCallBack的类,并在ngOnInit中使用此代码而不是像之前那样使用“this.animate()”。

this.animateCallback = {
      callAnimate: (this.animate).bind(this)
    };
    this.animateCallback.callAnimate();

并且animate功能更改为:

protected animate() {
    requestAnimationFrame( this.animateCallback.callAnimate );

    this.mesh.rotation.x += 1;
    this.mesh.rotation.y += 1;

    this.renderer.render( this.scene, this.camera );

  }

答案 1 :(得分:1)

/** * For a given function, creates a bound function that has the same body as the original function. * The this object of the bound function is associated with the specified object, and has the specified initial parameters. * @param thisArg An object to which the this keyword can refer inside the new function. * @param argArray A list of arguments to be passed to the new function. */ bind(this: Function, thisArg: any, ...argArray: any[]): any;

使用这个我的更新功能最终看起来像:

update () { // Schedule the next frame. requestAnimationFrame(this.update.bind(this)); // Draw! this.renderer.render(this.scene, this.camera); }