班上三个js

时间:2016-11-22 14:33:36

标签: javascript three.js

我尝试将所有必要的功能设置到一个类中,以便使用多维数据集创建一个简单的three.js场景。我没有收到任何错误,但是当我在浏览器中打开它时,场景保持黑色。 这是我的代码:

class SceneInit {

    constructor(fov = 45,camera,scene,controls,renderer)
    {
        this.camera = camera;
        this.scene = scene;
        this.controls = controls;
        this.renderer = renderer;
        this.fov = fov;

    }



    initScene() {
        this.camera = new THREE.PerspectiveCamera(this.fov, window.innerWidth / window.innerHeight, 1, 1000);
        this.camera.position.z = 15;

        this.controls = new THREE.TrackballControls( this.camera );
        //this.controls.addEventListener('change', this.renderScene);

        this.scene = new THREE.Scene();

        //specify a canvas which is already created in the HTML file and tagged by an id        //aliasing enabled
        this.renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myThreeJsCanvas') , antialias: true});
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(this.renderer.domElement);


        //ambient light which is for the whole scene
        let ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
        ambientLight.castShadow = false;
        this.scene.add(ambientLight);

        //spot light which is illuminating the chart directly
        let spotLight = new THREE.SpotLight(0xffffff, 0.55);
        spotLight.castShadow = true;
        spotLight.position.set(0,40,10);
        this.scene.add(spotLight);


        //if window resizes
        window.addEventListener('resize', this.onWindowResize, false);
    }


    animate(){
        requestAnimationFrame( this.animate.bind(this) );
        this.render();
        this.controls.update();
    }


    render(){
        this.renderer.render( this.scene, this.camera );
    }


    onWindowResize() {
    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize( window.innerWidth, window.innerHeight );
}

}

然后我尝试实例化一个新对象并将一个对象添加到场景中。当我尝试打印场景的孩子时,它会返回正确的对象,但正如我之前提到的,场景保持黑色。只有渲染器窗口才会在浏览器中绘制。

let test = new SceneInit(45);
test.initScene();
test.animate();


let geometry = new THREE.BoxBufferGeometry( 200, 200, 200 );
let material = new THREE.MeshBasicMaterial();
let mesh = new THREE.Mesh( geometry, material );

test.scene.add(mesh);
console.log(test.scene.children); //returns 3 objects (ambientLight, spotLight, mesh)

1 个答案:

答案 0 :(得分:1)

我得到了答案。

代码中的问题是BoxGeometry太大而且相机在盒子里面。将剪辑设置为1时,它甚至不会渲染它。 因此解决方案是设置较小的BoxGeometry。或移开相机!