我试图将三个实现到Angular 4环境中,我试图使用JSONLoader但无法正常工作,我正确定义了Json的路径,但我无法将其添加到场景中,“无法设置属性” mesh”在线上未定义的错误是即时消息正在获取的错误
let material = new THREE.MeshBasicMaterial({ color : 0xFFFFFF, wireframe: true });
let geometry = new THREE.JSONLoader();
geometry.load("./maniqui4.json", function(geometry, materials){
this.mesh = new THREE.Mesh(geometry, material);
this.scene.add(this.mesh);
});
错误在this.scene.add(this.mesh);行中。
我尝试添加一个Box几何体,并且渲染得很好,但是使用JSONLoader却没办法
这是我的组件
import { Component, OnInit, ElementRef, ViewChild} from '@angular/core';
import * as THREE from 'three';
@Component({
selector: 'canvasRender',
templateUrl: './canvas.component.html',
})
export class canvasComponent{
@ViewChild('container') elementRef: ElementRef;
private container : HTMLElement;
private scene: THREE.Scene;
private camera: THREE.PerspectiveCamera;
private renderer: THREE.WebGLRenderer;
private mesh : THREE.Mesh;
constructor(){
console.log(THREE);
}
ngOnInit(){
this.container = this.elementRef.nativeElement;
console.log(this.container);
this.init();
}
init(){
let screen = {
width : 100,
height : 300
},
view = {
angle : 45,
aspect : screen.width / screen.height,
near : 0.1,
far : 1000
};
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(view.angle, view.aspect, view. near, view.far);
this.renderer = new THREE.WebGLRenderer();
this.scene.add(this.camera);
this.camera.position.set(10,10,10);
this.camera.lookAt(new THREE.Vector3(0,0,0));
this.renderer.setSize(screen.width, screen.height);
this.container.appendChild(this.renderer.domElement);
let material = new THREE.MeshBasicMaterial({ color : 0xFFFFFF, wireframe: true });
let geometry = new THREE.JSONLoader();
geometry.load("./maniqui4.json", function(geometry, materials){
this.mesh = new THREE.Mesh(geometry, material);
this.scene.add(this.mesh);
});
this.render();
}
render(){
};
animate(){
};
};
最佳答案
在您的init()方法开始处添加var scope = this;
行,如下所示:
init(){
var scope = this;
// rest of your code
}
然后在init()方法中使用
this
更改对scope
的所有引用。现在加载程序看起来像这样,
geometry.load("./maniqui4.json", function(geometry, materials){
scope.mesh = new THREE.Mesh(geometry, material);
scope.scene.add(scope.mesh);
});
问题是,当您从JsonLoader的加载功能调用
this
时,您是在指的是JsonLoader本身,而不是您的canvasComponent类。关于javascript - Three.js和Angular4与JSONLoader,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47730823/