Three.js不渲染元素

时间:2018-02-27 18:37:26

标签: javascript typescript three.js

我正在使用带有打字稿的模块化Three.js。它会创建场景,但它不会在画布上呈现任何元素。这是我的代码:

import * as THREE from 'three/build/three.module'

class App {
    private scene = new THREE.Scene();
    private camera;
    private renderer = new THREE.WebGLRenderer();
    private container = document.getElementById('widget');

    constructor() {
        this._init();
        let geometry = new THREE.BoxGeometry(1, 1, 1);
        let material = new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true });
        let cube = new THREE.Mesh(geometry, material);
        this.scene.add(cube);

    }

    _init() {
        this.camera = new THREE.PerspectiveCamera(45, this.container.clientWidth / this.container.clientHeight, 1, 1000);
        this.camera.position.z = 5;
        this.scene.add(this.camera)
        this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
        this.container.appendChild(this.renderer.domElement);
    }
}

new App()

1 个答案:

答案 0 :(得分:0)

它没有呈现任何内容,因为您没有告诉它。

如果您看一下"入门" doc https://threejs.org/docs/#manual/introduction/Creating-a-scene,您应该注意到您只是在创建场景"部分。

你还需要做的是"渲染场景"该教程的一部分。

某处需要调用yourAppInstance.renderer.render()方法。您可以将App实例存储在变量

var myApp = new App()

myApp.renderer.render(myApp.camera, myApp.scene)

^不确定打字稿是如何工作的,你可能无法访问这些。

您也可以在构造函数

中执行此操作
constructor() {
    this._init();
    let geometry = new THREE.BoxGeometry(1, 1, 1);
    let material = new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true });
    let cube = new THREE.Mesh(geometry, material);
    this.scene.add(cube);
    this.renderer.render(this.camera,this.scene) // <-- add this

}