通过three.js实现简易3D打印模型切片展示

现在的页面展示要求越来越高,美的展示总能吸引更多的访客。最近在学习3D打印中的切片算法,刚刚入门,发现通过three.js框架可以很好展示出3D切片细节(虽然我做的比较简单)。

复制代码
//==========================================================
//导入three.js和mygeo.js文件(自定义几何体顶点和三角片信息)
//==========================================================

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth,window.innerHeight);
renderer.setClearColor("white");
document.body.appendChild(renderer.domElement);
//上面6行初始化场景、照相机及渲染器=========================


var axes = new THREE.AxisHelper(10);
scene.add(axes);
//上面两行画出辅助坐标系

//根据mygeo.js中的信息画自定义几何体
var geom = new THREE.Geometry();
geom.vertices = vertices;
geom.faces = faces;
geom.computeFaceNormals();
ma = new THREE.MeshBasicMaterial({color: 'black', wireframe: true});
var G = new THREE.Mesh(geom,ma);
scene.add(G);
//上面7行画出自定义的立体几何体

camera.position.x = 5;
camera.position.y = 6;
camera.position.z = 8;
camera.lookAt(scene.position);
//上面几行设置相机位置

//自定义的三角形片和Z=h截面总有2个交点
for(var h = 0.5;h <= 6;h += 0.5) { var intersection = new Array(); for(var F = 0;F < faces.length;F++) { var point1 = vertices[faces[F].a]; var point2 = vertices[faces[F].b]; var point3 = vertices[faces[F].c]; var surface = [point1,point2,point3]; if((surface[0].z-h)*(surface[1].z-h)<0) //0-1 { var m = (h-surface[0].z)/(surface[1].z-surface[0].z); var x = m * (surface[1].x-surface[0].x) + surface[0].x; var y = m * (surface[1].y-surface[0].y) + surface[0].y; var p = [x,y,h]; intersection.push(p); } if((surface[0].z-h)*(surface[2].z-h)<0) //0-2 { var m = (h-surface[0].z)/(surface[2].z-surface[0].z); var x = m * (surface[2].x-surface[0].x) + surface[0].x; var y = m * (surface[2].y-surface[0].y) + surface[0].y; var p = [x,y,h]; intersection.push(p); } if((surface[1].z-h)*(surface[2].z-h)<0) //1-2 { var m = (h-surface[1].z)/(surface[2].z-surface[1].z); var x = m * (surface[2].x-surface[1].x) + surface[1].x; var y = m * (surface[2].y-surface[1].y) + surface[1].y; var p = [x,y,h]; intersection.push(p); } } var material = new THREE.LineBasicMaterial({color: "red", linewidth: 6}); var geometry = new THREE.Geometry(); for(var i1=0;i1<intersection.length;i1++) { var p1 = new THREE.Vector3(); p1.set(intersection[i1][0],intersection[i1][1],intersection[i1][2]); geometry.vertices.push(p1); } var line = new THREE.Line(geometry,material); scene.add(line); } renderer.render(scene, camera);
复制代码

 

posted @   niokit  阅读(3195)  评论(2编辑  收藏  举报
点击右上角即可分享
微信分享提示