首页 前端知识 使用three.js 简单加载STL格式3D模型

使用three.js 简单加载STL格式3D模型

2024-03-04 10:03:29 前端知识 前端哥 509 507 我要收藏

上述是简单版本

 一、使用three.js中的STLLoader加载模块

引入three.js 引入STLLoader加载模块。

// 引入three.js
import * as THREE from 'three';
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader';

 const containers = ref(null);
 let scene, camera, renderer, controls, raycaster, mouse, size, distance, boundingBox, mesh, initialCameraPosition, initialCameraTarget, modelCenter, labelRenderer;

初始化场景,相机,渲染函数,鼠标控制等全局变量。

 在初始化方法中,将灯光,环境光,渲染容器,相机,鼠标控制等进行初始化帮绑定。

const initScene = () => {
            scene = new THREE.Scene();
            const bgColor = new THREE.Color("#e7e9e9");
            scene.background = bgColor;

            const ambient = new THREE.AmbientLight(0xffffff, 1);
            scene.add(ambient);

            const spotLight = new THREE.SpotLight(0xffffff, 1.0);
            spotLight.intensity = 2.0;
            spotLight.angle = Math.PI / 2;
            spotLight.position.set(0, 0, -200);
            scene.add(spotLight);

            const pointLight = new THREE.PointLight(0xffffff, 10);
            pointLight.position.set(400, 0, 0);
            scene.add(pointLight);

            const pointLightHelper = new THREE.PointLightHelper(pointLight, 10);
            scene.add(pointLightHelper);

            const directionalLight = new THREE.DirectionalLight(0xffffff, 2);
            directionalLight.position.set(200, 200, 200);
            scene.add(directionalLight);

            camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);

            renderer = new THREE.WebGLRenderer();
            renderer.antialias = true
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setPixelRatio(window.devicePixelRatio)
            containers.value.appendChild(renderer.domElement);

            labelRenderer = new CSS2DRenderer();
            labelRenderer.setSize(containers.value.offsetWidth, containers.value.offsetHeight);
            labelRenderer.domElement.style.position = 'absolute';
            // 相对标签原位置位置偏移大小
            labelRenderer.domElement.style.top = '0px';
            labelRenderer.domElement.style.left = '0px';
            // //设置.pointerEvents=none,以免模型标签HTML元素遮挡鼠标选择场景模型
            labelRenderer.domElement.style.pointerEvents = 'none';
            containers.value.appendChild(labelRenderer.domElement);


            controls = new OrbitControls(camera, renderer.domElement);
            controls.enableZoom = false;
            controls.enableRotate = true;
            raycaster = new THREE.Raycaster();
            mouse = new THREE.Vector2();
        };

然后就是渲染加载stl模块及加载模型。'/modle/1.stl' 这里既可以是静态文件还可以是文件地址。

这一块主要是对加载模型材质的选择,并对加载的模型进行了描边,需要注意的是模型的缩放因子也需要在描边上添加,以及后面模型测量尺寸的展示都要除以这个缩放因子才是实际的尺寸。

这里还涉及到一个相机的初始位置的设置,模型初始化加载后,是呈现一个倾斜角度展示的,而不是看到的正面。并且拿全局变量进行了记录。在后面交互功能,相当于重置模型位置时要是用。

const loadModel = () => {
            const loader = new STLLoader();
            loader.load('/modle/1.stl', (geometry) => {
                const material = new THREE.MeshPhongMaterial({
                    color: '#918b84',
                    side: THREE.DoubleSide,
                    specular: '#918b84',
                    shininess: 12
                });
                mesh = new THREE.Mesh(geometry, material);
                // var surfaceArea = computeSurfaceArea(geometry);
                // var volume = computeModelVolume(geometry);
                // console.log('表面积:', surfaceArea, "体积", volume.toFixed(3));

                // 缩放模型尺寸
                const scale = 0.4; // 缩放因子

                const edges = new THREE.EdgesGeometry(geometry); // 根据模型几何体生成边缘几何体
                const edgeMaterial = new THREE.MeshPhysicalMaterial({ color: 0x000000, linewidth: 2 });

                const edgeMesh = new THREE.LineSegments(edges, edgeMaterial); // 创建线条对象
                edgeMesh.scale.set(scale, scale, scale);
                scene.add(edgeMesh);
                mesh.scale.set(scale, scale, scale);
                // 计算模型边界
                boundingBox = new THREE.Box3().setFromObject(mesh);
                // 计算模型尺寸
                size = new THREE.Vector3();
                boundingBox.getSize(size);

                // 计算与边界框最远点的距离
                distance = size.length() * 2;
                // 计算辅助坐标轴中心位置
                modelCenter = new THREE.Vector3();
                boundingBox.getCenter(modelCenter);
                //设置旋转中心是模型的中心
                controls.target.copy(modelCenter);

                // 设置相机位置和目标点
                const cameraPosition = modelCenter.clone().add(new THREE.Vector3(1, 1, 1).normalize().multiplyScalar(distance));
                camera.position.copy(cameraPosition);
                camera.lookAt(modelCenter);
                initialCameraPosition = cameraPosition
                initialCameraTarget = modelCenter
                scene.add(mesh)
            });
        };

 const handleResize = () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
            labelRenderer.setSize(window.innerWidth, window.innerHeight);

        };

        const animate = () => {
            requestAnimationFrame(animate);
            controls.update();
            TWEEN.update();
            renderer.render(scene, camera);
            labelRenderer.render(scene, camera);
        };

最后一个是根据浏览器窗口重新设置尺寸,一个是调用渲染函数进行渲染,到此一个STL模型就加载出来了

转载请注明出处或者链接地址:https://www.qianduange.cn//article/3170.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!