I am trying to incorporate ThreeJs into my Angular 2 project. I have successfully rendered a scene with a simple cube, but I ran into an issue when using the animate() function. Here is the code snippet:
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 );
}
}
When calling this.animate() inside of ngOnInit(), the scene renders and applies rotation once. However, upon calling requestAnimationFrame, I encounter an error stating that "this" is undefined. It seems like the context of "this" referring to the class is lost.
My question is: Is there a correct or best practice to maintain the context of "this", or is there an alternative method to run the animation loop smoothly? Any help would be greatly appreciated!