vlambda博客
学习文章列表

ThreeJS——3D场景中插入多个几何体

小猿在上篇文章中介绍了用Three.js绘制一个正方体所需的步骤,在这里小猿将介绍在3D场景中插入多个新几何体。绘制几何体的步骤都是那些步骤,所不同的是,这些几何体绘制的方法不一样,所需的参数不同,在这里直接完整的代码展示。



完整代码如下

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <style> body{ margin: 0; overflow: hidden; }</style></head><body><script src="./../js/three.js"></script><script> /* * 创建场景对象Scene * */ let scene = new THREE.Scene();
// 立方体网格模型 let geometry1 = new THREE.BoxGeometry(100, 100, 100); let material1 = new THREE.MeshLambertMaterial({ color: 0x0000ff }); // 材质对象Material let mesh1 = new THREE.Mesh(geometry1, material1); // 网格模型对象Mesh1 scene.add(mesh1); // 网格模型添加到场景中
// 球体网格模型 let geometry2 = new THREE.SphereGeometry(60, 40, 40); let material2 = new THREE.MeshLambertMaterial({ color: 0xff00ff }); let mesh2 = new THREE.Mesh(geometry2, material2); // 网格模型对象Mesh2 mesh2.translateY(120); // 球体网格模型沿Y轴正方向平移120 scene.add(mesh2);
// 圆柱网格模型 let geometry3 = new THREE.CylinderGeometry(50, 50, 100, 25); let material3 = new THREE.MeshLambertMaterial({ color: 0xffff00 }); let mesh3 = new THREE.Mesh(geometry3, material3); // 网格模型对象Mesh3 mesh3.position.set(170, 0, 0); // 设置mesh3模型对象的xyz坐标为170,0,0 scene.add(mesh3);
// 正八面体 let geometry4 = new THREE.OctahedronGeometry(50); let material4 = new THREE.MeshLambertMaterial({ color: 0xffff00 }); let mesh4 = new THREE.Mesh(geometry4, material4); // 网格模型对象Mesh4 mesh4.position.set(-170, 0, 0); // 设置mesh4模型对象的xyz坐标为-170,0,0 scene.add(mesh4);
// 正十二面体 let geometry5 = new THREE.DodecahedronGeometry(50); let material5 = new THREE.MeshLambertMaterial({ color: 0xffff00 }); let mesh5 = new THREE.Mesh(geometry5, material5); // 网格模型对象Mesh5 mesh5.position.set(0, 0, -170); // 设置mesh5模型对象的xyz坐标为-170,0,0 scene.add(mesh5);
// 正二十面体 let geometry6 = new THREE.IcosahedronGeometry(50); let material6 = new THREE.MeshLambertMaterial({ color: 0xffff00 }); let mesh6 = new THREE.Mesh(geometry6, material6); // 网格模型对象Mesh6 mesh6.position.set(0, 0, 170); // 设置mesh6模型对象的xyz坐标为170,0,0 scene.add(mesh6);
/** * 光源设置 */ //点光源 let point = new THREE.PointLight(0xffffff); point.position.set(400, 200, 200); scene.add(point); //环境光 let ambient = new THREE.AmbientLight(0x444444); scene.add(ambient);
/** * 相机设置 */ let width = window.innerWidth; //窗口宽度 let height = window.innerHeight; let k = width / height; //窗口宽高比 let s = 200; // 创建相机对象 let camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000); camera.position.set(200, 300, 200); //设置相机位置 camera.lookAt(scene.position); //设置相机方向(指向的场景对象)
/** * 创建渲染器对象 */ let renderer = new THREE.WebGLRenderer(); renderer.setSize(width, height);//设置渲染区域尺寸 renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色 document.body.appendChild(renderer.domElement); // body元素中插入canvas对象 //执行渲染操作 指定场景、相机作为参数
let T0 = new Date() function renderModle() { let T1 = new Date() let t = T1 - T0 T0 = T1 requestAnimationFrame(renderModle) renderer.render(scene, camera) mesh1.rotateY(0.0001 * t) }
renderModle ()</script></body></html>


果图如下