基本的THREE.js场景设置

时间:2017-02-02 18:01:23

标签: three.js

我的问题很简单,但对于我的生活,我无法弄清楚发生了什么。我正在尝试设置一个基本的three.js场景并添加一个带有BaiscMaterial的简单立方体,但是立方体没有出现在我的场景中。

"use strict";
var renderer, scene, camera;
var light;

function init() {
    var canvasWidth = 850;
    var canvasHeight = 450;
    var canvasRatio = canvasWidth / canvasHeight;

    camera = new THREE.PerspectiveCamera(45, canvasRatio, 0.9, 1000);

    camera.position.set(0, 200, -550);
    camera.lookAt(0, 0, 0);

    light = new THREE.AmbientLight(0xFFFFFF, 1);
    light.position.set(-800, 900, 300);

    renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setSize(canvasWidth, canvasHeight);
    renderer.setClearColorHex(0x000000, 1.0); //canvas color

    renderer.gammaInput = true;
    renderer.gammaOutput = true;

}
function cube() {
    var cubeGeo = new THREE.CubeGeometry(1000, 1000, 1000);
    var cubeMaterial = new THREE.MeshBasicMaterial();
    var cube1 = new THREE.Mesh(cubeGeo, cubeMaterial);
    cube1.position.set(0, 0, 0);

    return cube1;

}
function fillScene() {

    scene = new THREE.Scene();
    scene.add(light);
    var cube = cube();
    scene.add(cube);


}
function addToDOM() {
    var container = document.getElementById('container');
    var canvas = container.getElementsByTagName('canvas');

    if (canvas.length > 0) {
        container.removeChild(canvas[0]);
    }
    container.appendChild(renderer.domElement);
}

function render() {
    fillScene();
    renderer.render(scene, camera);
}
try {
    init();
    fillScene();
    addToDOM();
    render();

} catch (e) {
    var errorReport = "Your Program encountered an ERROR, cannot draw on canvas. Error was:<br/><br/>";
    $('#container').append(errorReport + e);
}

1 个答案:

答案 0 :(得分:0)

首先,Cube现已更新为BoxGeometry。我发现你的代码有很多问题,功能定义和使用不当。

这是mr.doob的Github的一个非常简单的例子。

var scene, camera, renderer;
var geometry, material, mesh;

init();
animate();

function init() {

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.z = 1000;

    geometry = new THREE.BoxGeometry( 200, 200, 200 );
    material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );

    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );

    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.02;

    renderer.render( scene, camera );

}

请参阅演示here

P.S Three.js Docs是资源的最佳位置,通过大量示例代码,它使工作变得更加轻松。