渲染3維場景需要做的一些初始化操作:
var scene = new THREE.Scene(); // 定義場景
var camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000); // 定義相機(jī)
var renderer = new THREE.WebGLRenderer(); // 定義渲染器
renderer.setClearColorHex(0xEEEEEE); // setClearColorHex()函數(shù)將renderer的背景色設(shè)置為0xEEEEEE
renderer.setSize(window.innerWidth, window.innerHeight); // 通過setSize()函數(shù)告訴renderer需要多大的scene場景
接著,使用代碼來添加輔助的坐標(biāo)軸以及平面:
var axes = new THREE.AxisHelper(20); // 創(chuàng)建三個軸長度為20的坐標(biāo)系
scene.add(axes); // 添加至場景中
var planeGeometry = new THREE.PlaneGeometry(30, 40); // 創(chuàng)建寬30,高40的平面
var planeMaterial = new THREE.MeshBasicMaterial({color: 0x333333}); // 平面底色為0x333333
var plane = new THREE.Mesh(planeGeometry, planeMaterial); // 加入到網(wǎng)格對象中去
plane.rotation.x = -0.5 * Math.PI;
plane.position.x = 10;
plane.position.y = 0;
plane.position.z = 0;
scene.add(plane);
創(chuàng)建坐標(biāo)軸對象,使用scene.add()去將這些坐標(biāo)軸添加到我們的場景中去,通過new THREE.PlaneGeometry創(chuàng)建了一個寬30、高40的平面,在創(chuàng)建好平面之后,還需要設(shè)置平面的外觀,在three.js中可以通過創(chuàng)建材質(zhì)對象來達(dá)到這個目的,new THREE.MeshBasicMaterial中設(shè)置color值,將這兩種屬性對象合并到Mesh網(wǎng)格對象中,然后設(shè)置平面的視角,定義它在場景中的位置坐標(biāo),將它繞x軸旋轉(zhuǎn)90度,然后position定義它在場景中的位置。
創(chuàng)建方塊對象:
var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
var cubeMaterial = new THREE.MeshBasicMaterial({color: 0xf0f0f0, wireframe: true});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.x = -4;
cube.position.y = 3;
cube.position.z = 0;
scene.add(cube);
創(chuàng)建球狀對象:
var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
var sphereMaterial = new THREE.MeshBasicMaterial({color: 0x7777ff, wireframe: true});
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.x = 20;
sphere.position.y = 4;
sphere.position.z = 2;
scene.add(sphere);
調(diào)整相機(jī)視角位置并加入到渲染器中
camera.position.x = -30;
camera.position.y = 40;
camera.position.z = 30;
camera.lookAt(scene.position);
document.getElementById("WebGL-output").appendChild(renderer.domElement);
renderer.render(scene, camera);