• three.js 入门 初识


    基本步骤:

    1. 初始设置
    2. 创建场景
    3. 创建相机
    4. 创建可见对象
    5. 创建渲染器
    6. 渲染场景

    安装

    npm install three

    引入

    import * as THREE from "three";

    一、three三要素:场景、相机、渲染

    1.场景:

    1. //创建场景
    2. const scene=new THREE.Scene()

    2.相机:OrthographicCamera正交投影(不会改变实际物体的大小)和PerspectiveCamera透视投影(和人的观感感觉一样会有近大远小的效果)我们这里是使用的透视投影

    1. //创建相机
    2. const camera = new THREE.PerspectiveCamera(
    3. 75,
    4. window.innerWidth / window.innerHeight,
    5. 0.1,
    6. 1000
    7. );
    8. // 设置相机位置
    9. camera.position.set(0, 0, 10);

    75  视野:相机的视野有多宽,以度为单位;

    window.innerWidth / window.innerHeight  纵横比:场景的宽度与高度的比率;

    0.1  近剪裁平面:任何比这更靠近相机的东西都是不可见的;

    1000  远剪裁平面:任何比这更远离相机的东西都是不可见的;

    3.渲染

    1. // 初始化渲染器
    2. const renderer = new THREE.WebGLRenderer();
    3. //设置渲染器为全屏
    4. renderer.setSize(window.innerWidth, window.innerHeight);
    5. // 将webgl渲染的canvas内容添加到body
    6. document.body.appendChild(renderer.domElement);

    以上完成后就是创建一些物体或者是导入模型加载到场景中进行渲染

    二、创建可见对象

    1.Geometries(几何图形)

    举例:长方体(BoxGeometry)

    1. // 创建几何体
    2. const geometry = new THREE.BoxGeometry(1, 1, 1);

    球体(SphereGeometry)

    const sphereTexture = new THREE.SphereGeometry(1, 20, 20);

    平面(PlaneGeometry)

    const planeGeometry = new THREE.PlaneGeometry(1, 1, 200, 200);

    2.Lights(灯光)

    环境光AmbientLight(它的颜色会添加到整个场景和所有对象的当前颜色上

    1. const light = new THREE.AmbientLight(0x404040);
    2. scene.add(light);

    点光源PointLight(这种光源放出的光线来自同一点,且辐射方向四面八方,如蜡烛发出的光

    方向光DirectionalLight(也称作无限光,从这种光源发出的光线可以看做是平行的,如太阳光

    1. const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
    2. // 设置直线光源的照射位置
    3. directionalLight.position.set(10, 10, 10);
    4. scene.add(directionalLight);

    聚光灯SpotLight(这种光源的光线从一个椎体中射出,在被照射的物体上产生聚光的效果,如手电筒发出的光

    能形成阴影的光源只有DirectionalLightSpotLight;而相对地,能表现阴影效果的材质只有LambertMaterialPhongMaterial

    three.js中渲染阴影的开销比较大,所以默认物体是没有阴影的,需要单独开启。开启阴影的方法:

    • 将渲染器的shadowMapEnabled属性设置为true(告诉渲染器可以渲染阴影)
    • 将物体及光源的castShadow属性设置为true(告诉物体及光源可以透射阴影 物体投射阴影)
    • 将接收该阴影的物体的receiveShadow属性设置为true(告诉物体可以接收其他物体的阴影 物体接收阴影)

    3.Controls(控制器)

    轨道控制插件OrbitControls.js可以实现场景用鼠标交互,让场景动起来,控制场景的旋转、平移和缩放。

    1. // 导入控制器
    2. import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
    3. const controls = new OrbitControls(camera, renderer.domElement);
    4. controls.enableDamping = true;

    配置该插件之后实现的效果:

    操控效果
    按住鼠标左键并移动摄像机围绕场景中心旋转
    转动鼠标滑轮或按住中键并移动放大或缩小
    按住鼠标右键并移动在场景中平移
    上、下、左、右方向键在场景中平移

    4.Loaders(加载器)

    5.Textures(纹理)

    1. const textureLoader = new THREE.TextureLoader();
    2. const floorColor = textureLoader.load(require("../assets/img/door/color.jpg"));

    6.Materials(材质)

    1. // 材质
    2. const material = new THREE.MeshBasicMaterial({
    3. map: floorColor
    4. });

    MeshBasicMaterial(对光照无感,无光源可以显示,给几何体一种简单的颜色或显示线框)

    MeshLambertMaterial(对光照有反应,无光源则不会显示,用于创建暗淡的不发光的物体)MeshPhongMaterial(对光照有反应,无光源不会显示,用于创建金属类米昂凉的物体)

    物体之所以能被人眼看见,一种是它自身的材料就能发光,不需要借助外界光源;另一种是自身材料不发光,需要反射环境中的光。对于自身不发光的物体,需要个场景添加光源从而达到可视的效果。

    1. const geometry = new THREE.BoxGeometry(1,1,1); // 创建一个长宽高都为1个单位的立方体
    2. const textureLoader = new THREE.TextureLoader();//初始化纹理
    3. const floorColor = textureLoader.load(require("../assets/img/door/color.jpg"));//导入纹理为一张图片
    4. const material = new THREE.MeshBasicMaterial({color: 0x00ff00,map: floorColor}); // 创建材质,对光照无感
    5. const cube = new THREE.Mesh(geometry, material); // 创建一个立方体网格(mesh),将材质包裹在立方体上
    6. scene.add(cube); // 将立方体网格添加到场景中
    7. camera.position.z = 5; // 指定相机位置
    8. function animate() {
    9. // 照相机转动时,必须更新该控制器
    10. controls.update();
    11. // 结合场景和相机进行渲染,即用摄像机拍下此刻的场景
    12. renderer.render(scene, camera);
    13. // 渲染下一帧的时候就调用animate
    14. requestAnimationFrame(animate);
    15. }
    16. animate();

    7.坐标轴辅助器

    1. const axesHelper = new THREE.AxesHelper(5);
    2. scene.add(axesHelper);

    红色代表 X 轴. 绿色代表 Y 轴. 蓝色代表 Z 轴.5表示轴的线段长度

    8.监听画面变化

    1. // 监听画面变化
    2. window.addEventListener("resize", () => {
    3. const iwidth = window.innerWidth;
    4. const iheigt = window.innerHeight;
    5. //更新摄像头
    6. camera.aspect = iwidth / iheigt;
    7. // 更新摄像机投影矩阵
    8. camera.updateProjectionMatrix();
    9. // 更新渲染器
    10. renderer.setSize(iwidth, iheigt);
    11. // 设置渲染器像素比 防止在HiDPI显示器模糊(视网膜显示器)
    12. renderer.setPixelRatio(window.devicePixelRatio);
    13. });

    三、dat.gui控件(可以对渲染出来的物体进行变化操作)

    1.安装并引入gui

    1. npm install --save dat.gui
    2. import * as dat from "dat.gui";

    2.实例代码

    1. const gui = new dat.GUI();
    2. gui
    3. .add(cube.position, "x")
    4. .min(0)
    5. .max(5)
    6. .step(0.05)
    7. .name("移动x坐标")
    8. .onChange((value) => {
    9. console.log("值被修改了:", value);
    10. });
    11. // 修改物体的颜色
    12. const params = {
    13. color: "#fff",
    14. fn: () => {
    15. gsap.to(cube.position, {
    16. x: 5,
    17. ease: "power1.out",
    18. duration: 5,
    19. repeat: -1,
    20. yoyo: true,
    21. });
    22. },
    23. };
    24. gui.addColor(params, "color").onChange((value) => {
    25. cube.material.color.set(value);
    26. });
    27. // 设置是否显示
    28. gui.add(cube, "visible").name("是否显示");
    29. // 设置按钮点击触发某个事件
    30. var folder = gui.addFolder("设置立方体");
    31. folder.add(cube.material, "wireframe");
    32. folder.add(params, "fn").name("立方体运动");

    3.效果

    image.png

    四、环境贴图

    1. // 设置cube纹理加载器
    2. const cubeTextureLoader = new THREE.CubeTextureLoader();
    3. const envMapTexture = cubeTextureLoader.load([
    4. require("../assets/img/environmentMaps/1/px.jpg"),
    5. require("../assets/img/environmentMaps/1/nx.jpg"),
    6. require("../assets/img/environmentMaps/1/py.jpg"),
    7. require("../assets/img/environmentMaps/1/ny.jpg"),
    8. require("../assets/img/environmentMaps/1/pz.jpg"),
    9. require("../assets/img/environmentMaps/1/nz.jpg"),
    10. ]);// p-正方向,n-负方向
    11. // 创建球体
    12. const sphereTexture = new THREE.SphereGeometry(1, 20, 20);
    13. // 材质
    14. const material = new THREE.MeshStandardMaterial({
    15. metalness: 0.7,
    16. roughness: 0,
    17. });
    18. // 关联几何体和材质
    19. const spher = new THREE.Mesh(sphereTexture, material);
    20. // 添加几何体到场景
    21. scene.add(spher);
    22. // 给场景添加背景
    23. scene.background = envMapTexture;
    24. // 给场景所有的物体添加默认的环境贴图
    25. scene.environment = envMapTexture;

    五、HRD加载

    1. // 导入hdr加载器
    2. import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader'
    3. // 加载hdr环境图
    4. const rgbeLoader = new RGBELoader();
    5. rgbeLoader.loadAsync(require("../assets/img/hdr/012.hdr")).then((texture) => {
    6. texture.mapping = THREE.EquirectangularReflectionMapping; // 经纬线映射贴图
    7. scene.background = texture;
    8. scene.environment = texture;
    9. })

    六、加载3D模型

    1. import * as THREE from 'three'
    2. import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
    3. import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
    4. import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
    5. import robot from '../../public/robotglb.glb'
    6. const scene = new THREE.Scene()
    7. const camera = new THREE.PerspectiveCamera(
    8. 75,
    9. window.innerWidth / window.innerHeight,
    10. 0.1,
    11. 1000
    12. )
    13. camera.position.set(0, 0, 10)
    14. scene.add(camera)
    15. const light = new THREE.AmbientLight(0xffffff)
    16. scene.add(light)
    17. //初始化模型加载器
    18. const loader = new GLTFLoader()
    19. //解压模型
    20. const dracoLoader = new DRACOLoader()
    21. //引入文件
    22. dracoLoader.setDecoderPath('/draco/')
    23. loader.setDRACOLoader(dracoLoader)
    24. loader.load(
    25. robot,//模型
    26. gltf => {
    27. console.log(gltf, 'gltf')
    28. scene.add(gltf.scene)
    29. },
    30. xhr => {
    31. console.log(xhr)
    32. },
    33. err => {
    34. console.log(err)
    35. }
    36. )
    37. let mesh = new THREE.Mesh()
    38. mesh.scale.set(6,6,6)
    39. const renderer = new THREE.WebGLRenderer()
    40. renderer.setSize(window.innerWidth, window.innerHeight)
    41. document.body.appendChild(renderer.domElement)
    42. const controls = new OrbitControls(camera, renderer.domElement)
    43. function animate () {
    44. controls.update()
    45. renderer.render(scene, camera)
    46. requestAnimationFrame(animate)
    47. }
    48. animate()

    注意:

    这里的3d模型一定要放在public文件夹下不能放在src中 会报错 

  • 相关阅读:
    一、初识 Elasticsearch:概念,安装,设置分词器
    千卡利用率超98%,详解JuiceFS在权威AI测试中的实现策略
    百度千帆大模型文心一言api调用
    JavaEE初阶:网络原理之TCP/IP
    gitee的注册和代码提交
    VBA入门2——程序结构
    【每日一题Day42】生成交替二进制字符串的最小操作数 | 模拟 位运算
    psycopg2.pool.PoolError: connection pool exhausted
    React+Vis.js(01):实现基本的网络图
    十三、队列的特性
  • 原文地址:https://blog.csdn.net/killerdoubie/article/details/132894876