Three.js基础:导入STL模型文件
stlloadertest.html:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <title>three.js webgl - STL</title> 5 <script src="build/three.js"></script> 6 <script src="js/loaders/STLLoader.js"></script> 7 <script type="text/javascript" src="js/controls/OrbitControls.js"></script> 8 <script type="text/javascript" src="stlloadertest.js"></script> 9 </head> 10 11 <body onload="init()"> 12 <div> 13 <canvas id="mainCanvas" width="1000px" height="600px" ></canvas> 14 </div> 15 </body> 16 </html>
stlloadertest.js:
1 var camera, cameraTarget, scene, renderer,controlls,loader,material,mesh; 2 3 function init() { 4 5 //camera 6 camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 1000 ); 7 camera.position.set( 0, 0, 500 ); 8 9 cameraTarget = new THREE.Vector3( 0, 0, 0 ); 10 camera.lookAt( cameraTarget ); 11 12 //scene 13 scene = new THREE.Scene(); 14 scene.background = new THREE.Color( 0x72645b ); 15 scene.add(camera); 16 17 // renderer 18 renderer = new THREE.WebGLRenderer({ 19 canvas: document.getElementById('mainCanvas') 20 }); 21 22 renderer.setSize( window.innerWidth, window.innerHeight ); 23 24 25 26 // a cube in the scene 27 cube = new THREE.Mesh(new THREE.CubeGeometry(50, 50, 50), 28 new THREE.MeshBasicMaterial({ 29 color: 0xff0000 //red 30 }) 31 ); 32 cube.position.set(50,0,0); 33 scene.add(cube); 34 35 36 // ASCII file 37 //导入dayan.stl 39 loader = new THREE.STLLoader(); 40 loader.load( 'stl/ascii/dayan.stl', function ( geometry ) { 41 42 material = new THREE.MeshPhongMaterial( { color: 0xff5533, specular: 0x111111, shininess: 200 } ); 43 mesh = new THREE.Mesh( geometry, material ); 44 45 mesh.position.set( 1, 0, 0 ); 46 mesh.rotation.set( -Math.PI/2, 0, 0 ); 47 //Math.PI 48 mesh.scale.set( 1, 1, 1 ); 49 50 mesh.castShadow = true; 51 mesh.receiveShadow = true; 52 53 scene.add( mesh ); 54 55 render(); 56 57 } ); 58 59 60 // Lights 61 scene.add( new THREE.HemisphereLight( 0x443333, 0x111122 ) ); 62 addShadowedLight( 1, 1, 1, 0xffffff, 1.35 ); 63 64 //controlls 65 controls = new THREE.OrbitControls( camera ,renderer.domElement ); 66 controls.addEventListener( 'change', render ); 67 68 } 69 70 function addShadowedLight( x, y, z, color, intensity ) { 71 72 var directionalLight = new THREE.DirectionalLight( color, intensity ); 73 directionalLight.position.set( x, y, z ); 74 scene.add( directionalLight ); 75 76 directionalLight.castShadow = true; 77 78 var d = 1; 79 directionalLight.shadow.camera.left = -d; 80 directionalLight.shadow.camera.right = d; 81 directionalLight.shadow.camera.top = d; 82 directionalLight.shadow.camera.bottom = -d; 83 84 directionalLight.shadow.camera.near = 1; 85 directionalLight.shadow.camera.far = 4; 86 87 directionalLight.shadow.mapSize.width = 1024; 88 directionalLight.shadow.mapSize.height = 1024; 89 90 directionalLight.shadow.bias = -0.005; 91 92 } 93 94 function render() { 95 renderer.render( scene, camera ); 96 }