gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:14:57 24 4
gpt4 key购买 nike

我想在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com