123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379 |
- import * as THREE from 'three'; //导入整个 three.js核心库
- import {FBXLoader} from 'three/examples/jsm/loaders/FBXLoader';
- import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'; //导入控制器模块,轨道控制器
- import {CSS3DRenderer, CSS3DSprite} from 'three/examples/jsm/renderers/CSS3DRenderer.js';
- import {GUI} from 'three/examples/jsm/libs/lil-gui.module.min.js';
- import * as TWEEN from '@tweenjs/tween.js';
- import {getBottomMaterial} from './material.js';
- // 定义一个 class类
- class renderModel {
- constructor(selector) {
- this.container = document.querySelector(selector);
- // 相机
- this.camera;
- // 场景
- this.scene;
- //渲染器
- this.renderer;
- // 控制器
- this.controls;
- // 3d文字渲染器
- this.css3DRenderer = null;
- // 3d文字控制器
- this.css3dControls = null;
- // 模型
- this.model;
- // 环境光
- this.ambientLight;
- //模型平面
- this.planeGeometry;
- }
- // 初始化加载模型方法
- init() {
- //初始化场景
- this.initScene();
- //初始化相机
- this.initCamera();
- //初始化渲染器
- this.initRender();
- // 创建灯光
- this.createLight();
- //初始化控制器,控制摄像头,控制器一定要在渲染器后
- this.initControls();
- this.setFBXModel();
- //监听场景大小改变,跳转渲染尺寸
- window.addEventListener('resize', this.onWindowResizes);
- //场景渲染
- this.sceneAnimation();
- }
- //创建场景
- initScene() {
- this.scene = new THREE.Scene();
- this.scene.background = new THREE.Color(0x000000);
- const axesHelper = new THREE.AxesHelper(150);
- this.scene.add(axesHelper);
- //底部平面
- const geometry = new THREE.PlaneGeometry(1, 1);
- // 创建材质,可以设置贴图
- const material = getBottomMaterial(
- '#ffffff', // 设置模型的颜色
- require('@/assets/images/models/bg.png'),
- 1,
- 5
- );
- // 创建平面网格
- const plane = new THREE.Mesh(geometry, material);
- plane.scale.set(1000, 1000, 1000);
- plane.position.y = 0;
- const plane2 = plane.clone();
- plane2.material = getBottomMaterial(
- '#000000', // 设置模型的颜色
- require('@/assets/images/models/bg.png'),
- 2,
- 5
- );
- this.scene.add(plane2);
- this.scene.add(plane);
- }
- // 创建相机
- initCamera() {
- const {clientHeight, clientWidth} = this.container;
- this.camera = new THREE.PerspectiveCamera(18, clientWidth / clientHeight, 0.1, 10000);
- }
- // 创建渲染器
- initRender() {
- this.renderer = new THREE.WebGLRenderer({
- logarithmicDepthBuffer: true,
- antialias: true, // true/false表示是否开启反锯齿
- alpha: true, // true/false 表示是否可以设置背景色透明
- precision: 'mediump', // highp/mediump/lowp 表示着色精度选择
- premultipliedAlpha: true // true/false 表示是否可以设置像素深度(用来度量图像的分辨率)
- // preserveDrawingBuffer: false, // true/false 表示是否保存绘图缓冲
- // physicallyCorrectLights: true, // true/false 表示是否开启物理光照
- });
- //设置屏幕像素比
- this.renderer.setPixelRatio(window.devicePixelRatio);
- //渲染的尺寸大小
- const {clientHeight, clientWidth} = this.container;
- this.renderer.setSize(clientWidth, clientHeight);
- this.container.appendChild(this.renderer.domElement);
- // 创建一个CSS3渲染器CSS3DRenderer
- this.css3DRenderer = new CSS3DRenderer();
- this.css3DRenderer.setSize(clientWidth, clientHeight);
- // HTML标签<div id="tag"></div>外面父元素叠加到canvas画布上且重合
- this.css3DRenderer.domElement.style.position = 'absolute';
- this.css3DRenderer.domElement.style.top = '0px';
- this.css3DRenderer.domElement.style.zIndex = '9999';
- //设置.pointerEvents=none,解决HTML元素标签对threejs canvas画布鼠标事件的遮挡
- this.css3DRenderer.domElement.style.pointerEvents = 'none';
- this.css3DRenderer.domElement.style.className = 'css3DRenderer';
- this.container.appendChild(this.css3DRenderer.domElement);
- }
- // 创建光源
- createLight() {
- this.scene.add(new THREE.AmbientLight(0xffffff, 10));
- }
- initControls() {
- this.controls = new OrbitControls(this.camera, this.renderer.domElement);
- // this.controls.enableDamping = true;
- // this.controls.screenSpacePanning = false;
- // this.controls.maxPolarAngle = Math.PI / 1.1;
- // this.controls.minPolarAngle = Math.PI / 2;
- // this.controls.minAzimuthAngle = 0;
- // this.controls.maxAzimuthAngle = 0;
- // this.controls.maxDistance = 2000;
- //标签控制器
- this.css3dControls = new OrbitControls(this.camera, this.css3DRenderer.domElement);
- this.css3dControls.enablePan = false;
- this.css3dControls.enableDamping = true;
- this.controls.mouseButtons = {
- LEFT: THREE.MOUSE.PAN,
- MIDDLE: THREE.MOUSE.DOLLY,
- RIGHT: THREE.MOUSE.ROTATE
- };
- }
- animate() {
- this.renderer.render(this.scene, this.camera);
- this.controls.update();
- this.css3DRenderer.render(this.scene, this.camera);
- TWEEN.update();
- // // 检查模型位置是否发生变化
- // if (this.model) {
- // console.log('Model Position:', this.model.position);
- // console.log('Camera Position:', this.camera.position);
- // console.log('Controls Target:', this.controls.target);
- // }
- }
- // 使用动画器不断更新场景
- sceneAnimation() {
- this.renderer.setAnimationLoop(this.animate.bind(this));
- }
- initGUI() {
- const gui = new GUI();
- // 添加控制器目标位置的控制器
- const controlsFolder = gui.addFolder('Controls Target');
- controlsFolder
- .add(this.controls.target, 'x', -1000, 1000)
- .name('Target X')
- .onChange(() => {
- this.controls.update();
- });
- controlsFolder
- .add(this.controls.target, 'y', -1000, 1000)
- .name('Target Y')
- .onChange(() => {
- this.controls.update();
- });
- controlsFolder
- .add(this.controls.target, 'z', -1000, 1000)
- .name('Target Z')
- .onChange(() => {
- this.controls.update();
- });
- controlsFolder.open();
- // 添加相机位置的控制器
- const cameraFolder = gui.addFolder('Camera Position');
- cameraFolder
- .add(this.camera.position, 'x', -1000, 1000)
- .name('Camera X')
- .onChange(() => {
- this.controls.update();
- });
- cameraFolder
- .add(this.camera.position, 'y', -1000, 1000)
- .name('Camera Y')
- .onChange(() => {
- this.controls.update();
- });
- cameraFolder
- .add(this.camera.position, 'z', -1000, 1000)
- .name('Camera Z')
- .onChange(() => {
- this.controls.update();
- });
- cameraFolder.open();
- // 添加重置按钮
- const initialTarget = this.controls.target.clone();
- const initialCameraPosition = this.camera.position.clone();
- gui
- .add(
- {
- reset: () => {
- this.controls.target.copy(initialTarget);
- this.camera.position.copy(initialCameraPosition);
- this.controls.update();
- }
- },
- 'reset'
- )
- .name('Reset Position');
- }
- flyTo(target, scale = 1, duration = 1000) {
- const targetPosition = new THREE.Vector3().copy(target.position);
- const targetFocus = new THREE.Vector3().copy(target.targetContent);
- // 移动相机位置
- new TWEEN.Tween(this.camera.position)
- .to(targetPosition, target.time || 500)
- .easing(TWEEN.Easing.Quadratic.InOut)
- .onUpdate(() => {
- this.controls.update(); // 更新控制器
- })
- .start();
- // 移动控制器目标
- new TWEEN.Tween(this.controls.target)
- .to(targetFocus, target.time || 500)
- .easing(TWEEN.Easing.Quadratic.InOut)
- .onUpdate(() => {
- this.controls.update(); // 更新控制器
- })
- .start();
- new TWEEN.Tween(this.model.scale).to({
- x: scale,
- y: scale,
- z: scale
- }, duration).easing(TWEEN.Easing.Quadratic.InOut).start();
- }
- tag3D(name) {
- // 创建div元素(作为标签)
- let div = document.createElement('div');
- div.innerHTML = name;
- div.classList.add('tag3d');
- //div元素包装为CSS3模型对象CSS3DObject
- let label = new CSS3DSprite(div);
- div.style.pointerEvents = 'none'; //避免HTML标签遮挡三维场景的鼠标事件
- //缩放CSS3DObject模型对象
- label.scale.set(0.15, 0.15, 0.15); //根据相机渲染范围控制HTML 3D标签尺寸
- label.rotateY(Math.PI / 2); //控制HTML标签CSS3对象姿态角度
- return label; //返回CSS3模型标签
- }
- createDialog(html) {
- //div元素包装为CSS3模型对象CSS3DSprite
- const element = document.createElement('div');
- element.className = 'customDialog';
- element.appendChild(html);
- const dialog = new CSS3DSprite(element);
- element.style.pointerEvents = 'none'; //避免HTML标签遮挡三维场景的鼠标事件
- // 设置HTML元素标签在three.js世界坐标中位置
- // label.position.set(x, y, z);
- //缩放CSS3DSprite模型对象
- dialog.scale.set(0.15, 0.15, 0.15); //根据相机渲染范围控制HTML 3D标签尺寸
- dialog.rotateY(Math.PI / 2); //控制HTML标签CSS3对象姿态角度
- return dialog; //返回CSS3模型标签
- }
- /**
- * 设置加载模型居中
- * {Object} object 模型对象
- */
- setModelPosition(object) {
- object.updateMatrixWorld();
- // 获得包围盒得min和max
- const box = new THREE.Box3().setFromObject(object);
- // 返回包围盒的中心点
- const center = box.getCenter(new THREE.Vector3());
- object.position.x += object.position.x - center.x;
- object.position.y += object.position.y - center.y;
- object.position.z = 0;
- }
- setFBXModel() {
- var fbxLoader = new FBXLoader();
- fbxLoader.load('/models/model2.FBX', object => {
- this.calcMeshCenter(object);
- this.model = object;
- object.traverse(function (child) {
- if (child.isMesh) {
- child.material.emissive = child.material.color;
- child.material.emissiveMap = child.material.map;
- }
- });
- // 设置相机位置
- this.camera.position.set(-20, -652, 500);
- this.controls.target.set(-20, -20, 0);
- this.model.scale.set(1, 1, 1);
- // 设置相机坐标系
- this.camera.lookAt(0, 0, 0);
- // 将模型添加到场景中去
- this.scene.add(this.model);
- // window.addEventListener('click', event => {
- // const raycaster = new THREE.Raycaster();
- // const mouse = new THREE.Vector2();
- // mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
- // mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
- // raycaster.setFromCamera(mouse, this.camera);
- // const intersects = raycaster.intersectObjects(this.scene.children);
- // if (intersects.length > 0) {
- // const point = intersects[0].point;
- // console.log(`Clicked at: (${point.x}, ${point.y}, ${point.z})`);
- // }
- // });
- // this.initGUI();
- });
- }
- onWindowResizes() {
- if (!this.container) return false;
- const {clientHeight, clientWidth} = this.container;
- //调整屏幕大小
- this.camera.aspect = clientWidth / clientHeight; // 摄像机宽高比例
- this.camera.updateProjectionMatrix(); //相机更新矩阵,将3d内容投射到2d面上转换
- this.renderer.setSize(clientWidth, clientHeight);
- }
- calcMeshCenter(group) {
- /**
- * 包围盒全自动计算:模型整体居中
- */
- var box3 = new THREE.Box3();
- // 计算层级模型group的包围盒
- // 模型group是加载一个三维模型返回的对象,包含多个网格模型
- box3.expandByObject(group);
- // 计算一个层级模型对应包围盒的几何体中心在世界坐标中的位置
- var center = new THREE.Vector3();
- box3.getCenter(center);
- // 重新设置模型的位置,使之居中。
- group.position.x = 0;
- group.position.y = 0;
- group.position.z = 17;
- }
- addDialog(html, labelName, position) {
- const {x, y, z} = position
- const label3D = this.tag3D(labelName);
- const dialog3D = this.createDialog(html); //设置标签名称
- label3D.position.y += y;
- label3D.position.x += x;
- label3D.position.z += z;
- dialog3D.position.copy(label3D.position);
- dialog3D.position.z = z + 20;
- this.scene.add(label3D);
- this.scene.add(dialog3D);
- }
- }
- export default renderModel;
|