import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; import { ArrowHelper } from 'three'; // 初始化场景 export function initScene() { const scene = new THREE.Scene(); scene.background = new THREE.Color(230 / 255, 231 / 255, 233 / 255); // 设置背景颜色 return scene; } // 初始化相机 export function initCamera() { const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.set(100, 100, 300); // 调整相机位置 camera.lookAt(0, 0, 0); // 让相机看向点数据的中心 return camera; } // 初始化渲染器 export function initRenderer(container) { const renderer = new THREE.WebGLRenderer({ antialias: true }); // 可选:启用抗锯齿 console.log("container.clientWidth",container.clientWidth) const width = container.clientWidth || 775; // 获取容器的宽度 const height = container.clientHeight || 410; // 获取容器的高度 renderer.setSize(width, height); // 根据容器尺寸设置渲染器大小 container.appendChild(renderer.domElement); // 将渲染器的 DOM 元素添加到容器中 return renderer; } // 初始化轨道控制器 export function initControls(camera, renderer) { const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // 启用阻尼效果,使操作更平滑 controls.dampingFactor = 0.05; // 阻尼系数 controls.screenSpacePanning = true; // 允许平移 controls.minDistance = 10; // 最小缩放距离 controls.maxDistance = 8000; // 最大缩放距离 return controls; } // 创建坐标轴指示器 export function createAxesHelper(scene) { const axisLength = 50; // 坐标轴长度 const headLength = 15; // 箭头头部长度 const headWidth = 8; // 箭头头部宽度 const origin = new THREE.Vector3(0, 0, 0); // 原点 // X 轴(红色) const xAxis = new ArrowHelper( new THREE.Vector3(1, 0, 0), // 方向 origin, // 起点 axisLength, // 长度 0xff0000, // 颜色(红色) headLength, headWidth ); // Y 轴(绿色) const yAxis = new ArrowHelper( new THREE.Vector3(0, 1, 0), // 方向 origin, // 起点 axisLength, // 长度 0x00ff00, // 颜色(绿色) headLength, headWidth ); // Z 轴(蓝色) const zAxis = new ArrowHelper( new THREE.Vector3(0, 0, 1), // 方向 origin, // 起点 axisLength, // 长度 0x0000ff, // 颜色(蓝色) headLength, headWidth ); // 将坐标轴添加到场景中 scene.add(xAxis); scene.add(yAxis); scene.add(zAxis); } // 动画循环 export const animateScene = (scene, camera, renderer, controls) => { const animate = () => { requestAnimationFrame(animate); controls.update(); // 更新控制器 renderer.render(scene, camera); }; animate(); }; // 清理场景 export const cleanupScene = (renderer) => { if (renderer) { renderer.dispose(); } };