api:
代码:
<!DOCTYPE html> <html lang="en"> <head> <title>three.js webgl - loaders - 3DS loader</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <link type="text/css" rel="stylesheet" href="/three.js/main.css"> </head> <body> <script type="module"> //注意: //TrackballControls.js 和 TDSLoader.js 都引用了 three.module.js,特别注意引用的路径 import * as THREE from '/three.js/build/three.module.js'; import { TrackballControls } from '/three.js/jsm/controls/TrackballControls.js'; var container, controls; var camera, scene, renderer; init(); animate(); function resize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function animate() { controls.update(); renderer.render(scene, camera); requestAnimationFrame(animate); } function init() { container = document.createElement('div'); document.body.appendChild(container); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);// camera.position.z = 20; camera.position.x = 20; scene = new THREE.Scene(); var axis = new THREE.AxisHelper(3);//显示三维坐标系 scene.add(axis); var ambient = new THREE.AmbientLight(0xffffff);//环境光 scene.add(ambient); var geometry = new THREE.BoxBufferGeometry(1, 1, 1);//形状 var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });//材质 var mesh = new THREE.Mesh(geometry, material);//创建网格:网格 = 形状 + 材质 mesh.position.set(2, -2, 2);//设置网格的位置 scene.add(mesh);//将网格添加到场景 //模型居中 alert('3秒后模型自动居中!'); setTimeout(function () { mesh.geometry.computeBoundingBox(); var box = mesh.geometry.boundingBox.clone(); var mdlen = box.max.x - box.min.x; var mdwid = box.max.z - box.min.z; var mdhei = box.max.y - box.min.y; var centerpoint = new THREE.Vector3(); var x1 = box.min.x + mdlen / 2; var y1 = box.min.y + mdhei / 2; var z1 = box.min.z + mdwid / 2; mesh.position.set(-x1, -y1, -z1); }, 3000); renderer = new THREE.WebGLRenderer(); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); container.appendChild(renderer.domElement); controls = new TrackballControls(camera, renderer.domElement); window.addEventListener('resize', resize, false); } </script> </body> </html>
居中前:
居中后: