ThreeJs使用教程

简介

Three.js 是一款运行在浏览器中的3D 引擎,你可以用它创建各种三维场景,包括了摄影机、光影、材质等各种对象。three.js,一个WebGL引擎,基于JavaScript,可直接运行GPU驱动游戏与图形驱动应用于浏览器。其库提供大量特性与API以绘制3D场景于浏览器。

安装依赖

yarn add three@0.142.0

页面使用

<template>
    <div class="three-box">
        <div
            ref="points"
            id="points"
            class="points-box"
        >
        </div>
    </div>
</template>
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { DragControls } from 'three/examples/jsm/controls/DragControls'; // 拖拽控件
import { TransformControls } from 'three/examples/jsm/controls/TransformControls'; // 可视化平移控件
import { CSS3DRenderer, CSS3DObject } from 'three/examples/jsm/renderers/CSS3DRenderer.js'; // CSS3D
export default {
    components: {},
    props: {},
    data() {
        return {
            container: null, //容器
            camera: null, //相机
            scene: null, //场景
            renderer: null, //渲染器
            controls: null, //控制器
            cameraTarget: null, //相机方向
            width: null,
            height: null,
            lineGroup: null, // Target实线组
            LineSegmentsGroup: null, // Base虚线组
            PointsGroup: null, // Distance端点组
            top: -100,
            left: -100,
            name: '',
            targetX: null,
            targetY: null,
        };
    },
    mounted() {
        this.$nextTick(() => {
            this._initData();
            this.animate();
        });
    },
    beforeDestroy() {},
    methods: {
        _initData() {
            this.container = document.createElement('div');

            this.$refs.points.appendChild(this.container);
            this.width = this.$refs.points.offsetWidth;
            this.height = this.$refs.points.offsetHeight;
            //配置相机
            this.camera = new THREE.PerspectiveCamera(45, this.width / this.height, 1, 10000);
            this.camera.position.set(0, 0, 2200); //通过设置相机的位置转换视角,可以看到物体的不同角度
            this.cameraTarget = new THREE.Vector3(0, 0, 0);

            this.controls = new OrbitControls(this.camera, this.container);

            this.controls.addEventListener('change', this._rendergl, true); //通过控制鼠标操作模型的旋转缩放
            this.controls.update();

            this.controls.enableRotate = false; //禁止旋转

            //创建场景,设置背景色
            this.scene = new THREE.Scene();
            this.scene.background = new THREE.Color(0x696969);

            //网格坐标
            // var helper = new THREE.GridHelper( 1200, 60, 0xFF4444, 0x404040 );
            // this.scene.add( helper )

            //三维直角坐标系
            var axisHelper = new THREE.AxesHelper(2);
            this.scene.add(axisHelper);

            //设置灯源
            let spotLight = new THREE.SpotLight(0xffffff);
            spotLight.position.set(-100, -100, -100);

            let spotLight2 = new THREE.SpotLight(0xffffff);
            spotLight2.position.set(100, 100, 100);

            this.scene.add(spotLight);
            this.scene.add(spotLight2);

            this.scene.add(new THREE.HemisphereLight(0x443333, 0x111122));

            //渲染器
            this.renderer = new THREE.WebGLRenderer({ antialias: true }); //antialias是否开启反锯齿,设置为true开启反锯齿。
            this.renderer.setPixelRatio(window.devicePixelRatio); //设置设备像素比
            this.renderer.setSize(this.width, this.height);

            // this.renderer.gammaInput = true;    //全部的纹理和颜色预乘伽马,默认false
            // this.renderer.gammaOutput = true;   //须要以预乘的伽马输出,默认false

            this.renderer.shadowMap.enabled = true;

            this.container.appendChild(this.renderer.domElement);

            // resize
            window.addEventListener('resize', this.onWindowResize, false);
            window.addEventListener('mousewheel', this.onMousewheel, true); //通过控制鼠标操作模型的旋转缩放

            // 加载模型
            this._loadLine();

            this.raycaster = new THREE.Raycaster();
            this.pointer = new THREE.Vector2();
            // pointermove  pointerdown
            // window.addEventListener('pointermove', this.onPointerMove, true);
            this.container.addEventListener('pointerdown', this.onPointerMove, true);
        },
        onPointerMove(event) {
            // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
            let mainCanvas = document.getElementsByTagName('canvas')[0];
            // 将屏幕坐标转为标准设备坐标(支持画布非全屏的情况)
            this.pointer.x = ((event.clientX - mainCanvas.getBoundingClientRect().left) / mainCanvas.offsetWidth) * 2 - 1;
            this.pointer.y = -((event.clientY - mainCanvas.getBoundingClientRect().top) / mainCanvas.offsetHeight) * 2 + 1;

            var vector = new THREE.Vector3(this.pointer.x, this.pointer.y);
            vector = vector.unproject(this.camera); // 将屏幕的坐标转换成三维场景中的坐标
            var raycaster = new THREE.Raycaster(this.camera.position, vector.sub(this.camera.position).normalize());
            var intersects = raycaster.intersectObjects(this.scene.children, true);
            if (intersects.length > 0) {
                for (let item of intersects) {
                    if (item.object.type == 'Mesh') {
                        let array = item.object.name.split(',');
                        this.name = array[4];
                        this.targetX = array[2];
                        this.targetY = array[3];
                        this.top = event.offsetY - 50;
                        this.left = event.offsetX - 76;
                    } else {
                        this.top = -100;
                        this.left = -100;
                    }
                }
            } else {
                this.top = -100;
                this.left = -100;
            }
        },
        // 绘制线段
        _loadLine() {
            // Target材质 绿色实线
            const material = new THREE.LineBasicMaterial({ color: 0x00ff44 });
            // Base材质 灰色虚线
            const distanceMaterial = new THREE.LineDashedMaterial({
                color: 0xdbdbdb,
                dashSize: 3,
                gapSize: 1,
            });
            // Distance材质 偏差值内为绿色点 大于偏差值是红色点
            const redMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
            const greenMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff44 });
            const yellowMaterial = new THREE.MeshBasicMaterial({ color: 0xffeb00 });

            this.lineGroup = new THREE.Group();
            this.LineSegmentsGroup = new THREE.Group();
            this.PointsGroup = new THREE.Group();
            this.PointsGroup.name = 'Points';

            this.breakData.forEach((item, index) => {
                let points = [];
                points.push(new THREE.Vector3(item[0], item[1], 1));
                points.push(new THREE.Vector3(item[2], item[3], 1));
                let geometry = new THREE.BufferGeometry().setFromPoints(points);
                let line = new THREE.Line(geometry, material);
                this.PointsGroup.add(line);
                this.PointsGroup.visible = true;
                this.scene.add(this.PointsGroup);

                // 虚线
                // let topDashedPoints = [];
                // topDashedPoints.push(new THREE.Vector3(item[0], item[1], 0));
                // topDashedPoints.push(new THREE.Vector3(this.lower[index][0], this.lower[index][1], 0));
                // let topGeometry = new THREE.BufferGeometry().setFromPoints(topDashedPoints);
                // let topLine = new THREE.LineSegments(topGeometry, distanceMaterial);
                // // 计算LineDashedMaterial所需的距离的值的数组。
                // topLine.computeLineDistances();
                // this.LineSegmentsGroup.add(topLine);
                // this.LineSegmentsGroup.visible = true;
                // this.scene.add(this.LineSegmentsGroup);

                // Base
                let topPointsGeometry = new THREE.CircleGeometry(2, 32);
                let Points1 = new THREE.Mesh(topPointsGeometry, yellowMaterial);
                Points1.position.x = item[0];
                Points1.position.y = item[1];
                Points1.position.z = 0;
                Points1.name = item.toString();
                this.LineSegmentsGroup.add(Points1);
                this.LineSegmentsGroup.visible = true;
                this.scene.add(this.LineSegmentsGroup);

                // Target
                let bottomMaterial = this.distance > item[4] ? greenMaterial : redMaterial;
                let bottomPointsGeometry = new THREE.CircleGeometry(2, 32);
                let Points2 = new THREE.Mesh(bottomPointsGeometry, bottomMaterial);
                Points2.position.x = item[2];
                Points2.position.y = item[3];
                Points2.position.z = 1;
                Points2.name = item.toString();
                this.lineGroup.add(Points2);
                this.lineGroup.visible = true;
                this.scene.add(this.lineGroup);
            });
            this.renderer.render(this.scene, this.camera);

            // this.initDragControls();
        },
        // 添加拖拽控件
        initDragControls() {
            // 添加平移控件
            var transformControls = new TransformControls(this.camera, this.renderer.domElement);
            this.scene.add(transformControls);

            // 过滤不是 Mesh 的物体,例如辅助网格
            var objects = [];
            for (let i = 0; i < this.scene.children.length; i++) {
                if (this.scene.children[i].isLine || this.scene.children[i].isLineSegments || this.scene.children[i].isPoints) {
                    objects.push(this.scene.children[i]);
                }
            }
            // 初始化拖拽控件
            var dragControls = new DragControls(objects, this.camera, this.renderer.domElement);

            // 鼠标略过事件
            dragControls.addEventListener('hoveron', function (event) {
                console.log(event);
                // 让变换控件对象和选中的对象绑定
                transformControls.attach(event.object);
            });
            // 开始拖拽
            dragControls.addEventListener('dragstart', function (event) {
                controls.enabled = false;
            });
            // 拖拽结束
            dragControls.addEventListener('dragend', function (event) {
                controls.enabled = true;
            });
        },
        //监听屏幕大小变换
        onWindowResize() {
            this.$nextTick(() => {
                if (this.$refs.points) {
                    this.width = this.$refs.points.offsetWidth;
                    this.height = this.$refs.points.offsetHeight;
                    this.camera.aspect = this.width / this.height;
                    this.camera.updateProjectionMatrix();
                    this.renderer.setSize(this.width, this.height);
                }
            });
        },
        onMousewheel() {
            this.top = -100;
            this.left = -100;
        },
        //渲染函数
        _rendergl() {
            this.renderer.render(this.scene, this.camera);
        },
        //运动
        animate() {
            requestAnimationFrame(this.animate);
            this._rendergl();
        },
        //设置模型居中显示
        centerModel(group) {
            /**
             * 包围盒全自动计算:模型整体居中
             */
            var box3 = new THREE.Box3();
            // 计算层级模型group的包围盒
            // 模型group是加载一个三维模型返回的对象,包含多个网格模型
            box3.expandByObject(group);
            // 计算一个层级模型对应包围盒的几何体中心在世界坐标中的位置
            var center = new THREE.Vector3();
            box3.getCenter(center);
            // console.log('查看几何体中心坐标', center);

            // 重新设置模型的位置,使之居中。
            group.position.x = group.position.x - center.x;
            // group.position.y = group.position.y - center.y
            group.position.z = group.position.z - center.z;
        },
    },
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: three.js Editor 是一个基于 three.js 的在线编辑器,可以帮助开发者创建和编辑 3D 场景。它提供了一个直观的用户界面,允许开发者通过简单拖放和调整来添加模型、灯光、材质等,并在实时渲染中观察场景。 three.js Editor 的教程有助于初学者从基础开始学习如何使用该编辑器。下面是一些常见的教程内容: 1. 场景创建与配置:教程会介绍如何创建一个空白的场景,设置场景的背景颜色、光照、相机等。 2. 模型导入与编辑:教程会教你如何导入外部模型文件,并对导入的模型进行缩放、旋转、平移和删除等操作。 3. 材质与纹理编辑:教程会讲解如何为模型添加材质,并对材质进行编辑,包括颜色、贴图、透明度等属性的调整。 4. 动画与动态效果:教程会演示如何创建简单的动画效果,如模型的旋转、平移、缩放以及透明度的变化等。 5. 导出与部署:教程会指导如何将编辑好的场景导出为可执行的 HTML 文件,并将其嵌入到网页中展示,以及如何将其部署到网络服务器上。 除了上述内容,还会涉及一些高级的功能和技巧,如自定义着色器、创建物理效果、使用建模工具等。教程通常包括文字说明、示例代码和实际演示,帮助开发者更好地理解和掌握 three.js Editor 的使用技巧。 总之,通过 three.js Editor 的教程,开发者可以学习如何使用该编辑器创建交互性和视觉效果丰富的 3D 场景,并应用到自己的项目中。该教程既适合初学者入门学习,也适合有一定基础的开发者进阶学习。 ### 回答2: three.js Editor是一个基于Web的3D建模和动画工具,它可以帮助用户快速、轻松地创建和编辑3D场景。以下是关于three.js Editor的简要教程。 首先,进入three.js Editor的官方网站,下载并引入three.js库和Editor的插件文件。然后,创建一个DIV容器,用于显示3D场景。 在代码中,初始化一个场景对象、一个渲染器和一个相机,并将它们添加到DOM容器中。接下来,设置相机的位置和目标,以及渲染器的大小和背景色。 在场景中添加各种几何体、材质和灯光,可以使用Editor提供的工具栏或键盘快捷键进行操作。选中一个对象后,可以对它进行平移、旋转和缩放等变换操作,也可以改变其材质和光照属性。 通过场景对象的traverse方法,可以遍历场景中的所有对象,并对它们进行一系列操作。例如,可以通过编程方式创建和移除对象,或者检查对象之间的碰撞关系。 此外,Editor还提供了一个时间轴,用于创建和编辑动画。可以通过向时间轴添加关键帧来定义对象的动画路径和属性变化。可以使用插值算法对关键帧之间的属性进行平滑过渡,从而使动画更加流畅。 最后,通过监听鼠标、键盘等输入事件,可以实现用户交互。例如,通过鼠标左键拖拽场景中的对象,可以改变其位置。通过方向键控制相机的移动,可以浏览整个场景。 总结来说,three.js Editor是一个功能强大的3D建模和动画工具,通过它可以在Web上创建精美的3D场景。希望以上简要教程能够帮助您入门和使用three.js Editor。如果想要进一步学习和探索,建议参考官方文档和示例代码。 ### 回答3: three.js editor是一个基于three.js库的可视化编辑器工具,用于创建和编辑三维场景。它提供了一个直观易用的界面,可以帮助用户轻松地导入和管理模型、纹理等资源,以及创建、调整和组织场景中的物体和光源。 使用three.js editor的第一步是了解其基本概念和功能。官方文档中有详细的说明和示例,可以从中学习如何使用编辑器。另外,也可以在社区论坛或开发者的博客中找到一些优秀的教程和案例,这些内容可以帮助您更深入地了解编辑器的用法和技巧。 在使用编辑器的过程中,您需要掌握一些基本的三维图形概念,比如坐标系、材质、光照等。这些知识可以在学习three.js库的基础知识时了解到。同时,编辑器还提供了一些工具和选项,以便更好地处理场景中的对象和材质属性,比如实时渲染器、材质编辑器等。 为了更好地理解和使用编辑器,构建自己的项目是非常重要的。您可以从简单的场景开始,尝试不同的对象和材质配置,通过实践来熟悉编辑器的各种功能。随着经验的积累,您还可以尝试更复杂的场景,添加交互功能或特效等,以展示更丰富的三维体验。 总之,通过学习three.js editor的基本概念和功能,以及通过实践构建自己的项目,您将逐渐掌握使用该编辑器的技巧和技能。同时,多参与社区讨论和学习,与其他开发者分享经验和资源,也是提升自己的宝贵途径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值