var renderer = new THREE.WebGLRenderer({
canvas: document.getElementById('mainCanvas')
});
renderer.setClearColor(0x000000); // black
// 创建场景
var scene = new THREE.Scene();
// 创建相机
var camera = new THREE.PerspectiveCamera(45, 4 / 3, 1, 1000);
camera.position.set(0, 0, 5);
scene.add(camera); // 记得把相机添加到场景
// 创建一个长方形
var cube = new THREE.Mesh(new THREE.CubeGeometry(1, 2, 3),
new THREE.MeshBasicMaterial({
color: 0xff0000
})
);
scene.add(cube);
// 渲染器最终渲染
renderer.render(scene, camera);
现实中会有光源照射物体,产生光影效果,这里也可以添加 light。
var renderer = new THREE.WebGLRenderer({
canvas: document.getElementById('mainCanvas')
});
renderer.setClearColor(0xffcc00);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
// scene
var scene = new THREE.Scene();
// 添加环境光
var light = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(light);
// 添加点光源
var light2 = new THREE.PointLight(0xffffff, 0.7);
scene.add(light2);
// camera
var camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 0.1, 3000);
// camera.position.set(0, 0, 5);
var geometry = new THREE.CubeGeometry(200, 200, 200);
// var material = new THREE.MeshBasicMaterial();
var material = new THREE.MeshLambertMaterial({color: 0xffffee});
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, 0, -1000);
scene.add(mesh);
//
requestAnimationFrame(render)
function render() {
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
// render
renderer.render(scene, camera);
requestAnimationFrame(render)
}
总结
Threejs开发过程初步可归纳为
1、设置照相机 camera = new THREE.Camera(); 用于观察物体 2、设置场景 scene = new THREE.Scene() 用于承载物体 3、建立物体 geometry = new THREE.CubeGeometry(200, 200, 200); 4、创建网格 mesh = new THREE.Mesh(geometry, material) 5、渲染呈现 renderer.render(scene, camera)