three.js是一个用于在浏览器上绘制3d图像的js库,基于JavaScript和webgl。可以在网页上创建包含3d模型的视觉效果

copy_F3AC7612-8E14-4360-BB29-CA708EC47C73.gif

项目灵感和方法来源于这个视频:建立一个令人兴奋的 3D 作品集网站(Three.js初学者教程)_哔哩哔哩_bilibili

一、安装three.js

使用npm包管理器安装(更快捷且功能完整)或者在github上将相应源码复制到项目中(仅在需要更高灵活性和体积优势时使用)

二、three基本操作

在你的html文件中创建一个canvas元素,用来放置3d场景

<canvas id="bg"></canvas>

在js文件中设置3d场景

创建一个场景

const scene = new THREE.Scene();

设置场景背景颜色

scene.background = new THREE.Color(0xc5b8bf);

创建一个相机(一共有三种相机,这里的是透视相机)

const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.01, 1000);

创建一个渲染器

const renderer = new THREE.WebGLRenderer({
  canvas: document.querySelector('#bg'),
});

renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );

创建光源(有多种光源,如点光源,聚光灯,环境光等)

const pointlight = new THREE.PointLight(0xffffff, 800);
pointlight.position.set(-20, 15, 20)

const ambientlight = new THREE.AmbientLight(0xffffff, 2);
scene.add(pointlight, ambientlight)

设置aminate展示场景效果

function animate() {
  requestAnimationFrame( animate );
  renderer.render( scene, camera );
}
animate()

使用灯光helper可以显示光源位置

const lightHelper = new THREE.PointLightHelper(pointlight);
const gridHelper = new THREE.GridHelper(200, 50)
scene.add(lightHelper, gridHelper)

引入OrbitControls,可以直接在网页上控制视角位置

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
const controls = new OrbitControls(camera, renderer.domElement)
function animate() {
  requestAnimationFrame( animate );
  controls.update();
  renderer.render( scene, camera );
}

引入外部模型(这里是gltf格式的模型)

从项目目录中引入模型并加载到scene中

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
const loader = new GLTFLoader();

// 通过 loader 加载 glTF 模型
loader.load(
  '/models/scene.gltf', // 模型的路径
  function (gltf) {
    const model = gltf.scene;
    model.scale.set(15, 15, 15); 
    scene.add(model);  // 将加载的模型添加到场景中
  },
  undefined,
  function (error) {
    console.error('An error happened', error); // 错误处理
  }
);