问题:
为什么没有3D图形渲染?
详细信息:
我正在尝试加载this的json格式loading.component.ts 文件中的图形。我正在使用 Angular 2 和 Three.js。我看过几个例子,但找不到我做错了什么。这是我第一次尝试加载 3D 图像。任何帮助表示赞赏。 整个项目可以找到here .
控制台错误:
core.es5.js:1084 ERROR TypeError: Cannot read property 'scene' of undefined
at loading.component.ts:46
at ObjectLoader.parse (three.module.js:33413)
at three.module.js:33372
at XMLHttpRequest.<anonymous> (three.module.js:29460)
at ZoneDelegate.invokeTask (polyfills.bundle.js:3132)
at Object.onInvokeTask (core.es5.js:4119)
at ZoneDelegate.invokeTask (polyfills.bundle.js:3131)
at Zone.runTask (polyfills.bundle.js:2899)
at XMLHttpRequest.ZoneTask.invoke (polyfills.bundle.js:3194)
loading.component.ts
import { Component, OnInit } from '@angular/core';
import * as THREE from 'three'
declare var require: any;
@Component({
selector: 'app-loading',
templateUrl: './loading.component.html',
styleUrls: ['./loading.component.css']
})
export class LoadingComponent implements OnInit {
"use strict";
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer();
light = new THREE.AmbientLight(0xffffff);
camera;
box;
renderCallback;
constructor() { }
ngOnInit() {
// size of content
this.renderer.setSize( window.innerWidth, window.innerHeight);
// where to render content
document.getElementById("webgl-container").appendChild(this.renderer.domElement);
this.scene.add(this.light);
this.camera = new THREE.PerspectiveCamera(
35, // Field of view (FOV) from top to bottom.
window.innerWidth / window.innerHeight, // boundries of image
1,
1000
);
this.camera.position.set(0, 0, 5);
this.scene.add(this.camera);
var loader = new THREE.ObjectLoader();
loader.load('assets/img/pac-man-threejs/pac-man.json', function (obj) {
this.scene.add(obj);
})
// this.render();
this.renderCallback = {
callRender: (this.render).bind(this)
};
this.renderCallback.callRender();
}
render() {
this.renderer.render(this.scene, this.camera);
// requestAnimationFrame(this.render);
requestAnimationFrame(this.renderCallback.callRender);
}
}
最佳答案
您在 loader.load()
回调中没有正确的 this
,而这正是浏览器告诉您的内容。
var _this = this
loader.load(..., function(obj){ _this.scene.add(obj })
或者绑定(bind)它。
关于javascript - 无法使用 Three.js 渲染 3D 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44168284/