javascript - ThreeJs animate 在 Angular 2 中丢失上下文

标签 javascript angular typescript three.js

我想在 Angular 2 中使用 ThreeJs。我可以获得场景和一个简单的立方体来渲染,但是当使用 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”引用该类的上下文似乎丢失了。

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

最佳答案

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

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

并且动画函数更改为:

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

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

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

  }

关于javascript - ThreeJs animate 在 Angular 2 中丢失上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40893865/

相关文章:

javascript - Vue - 复选框全部处理选择的全局编辑 - 对象粘贴

javascript - 文本字段中的可点击图像

angular - 错误 TypeError : this. Remember.forEach 不是 AuthFormComponent.ngAfterContentInit 中的函数

处理未知变量的 TypeScript 错误 : Property does not exist on type 'object'

javascript - 如何根据选择值从数组中填充选择选项?

angular - Angular 2 中未定义错误提供

javascript - 在 chartjs 中,点在顶部和底部的边缘被减半

javascript - Office-JS 可以触发 VBA 工作簿或工作表事件过程吗?

Ionic 中的 Angular 2 react 形式复选框验证

javascript - 我如何检测 ngShow DOM 更改是否已完成?