Reputation: 3
Im trying to implement three into an Angular 4 environment, im trying to use a JSONLoader but is not working, i have the path defined to the Json correctly etc but i can´t add it to the scene, "cannot set property "mesh" of undefined on line is the error im getting at the moment
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);
});
The error is in the line this.scene.add(this.mesh);
i tried adding a Box geometry and it rendered fine, but no way with a JSONLoader
here is my component
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(){
};
};
Upvotes: 0
Views: 242
Reputation: 707
Add the line var scope = this;
at the start of your init() method, like this,
init(){
var scope = this;
// rest of your code
}
then change all the references to the this
with scope
inside the init() method.
Now the loader will look like this,
geometry.load("./maniqui4.json", function(geometry, materials){
scope.mesh = new THREE.Mesh(geometry, material);
scope.scene.add(scope.mesh);
});
The problem is that when you call this
from the load function of JsonLoader, you are referring to the JsonLoader itself, not to your canvasComponent class.
Upvotes: 1