Start - 开始ThreeJs之旅
Rendering and viewing a 3D object
要组成一个3D画面,需要3个主要元素:
- 场景 Scene
Store and keep track of all the objects we want to render and all the lights we want to use
1
const scene = new THREE.Scene()
- 相机 Camera
Defines what we’ll see when we render a scene
1
const camera = new THREE.PerspectiveCamera( 45, window.innerWidth/window.innerHeight, 0.1, 1000 )
- 渲染器 Renderer
Calculating what the scene object will look like
1
2
3const renderer = new THREE.WebGLRenderer()
renderer.setClearColor(new THREE.Color(0x000000))
renderer.setSize(window.innerWidth, window.innerHeight)
Renderers
ThreeJs提供多种渲染器:
- WebGLRenderer
- CanvasRenderer
- SVGRenderer
- CssRenderer
AxesHelper 坐标辅助器
a helpful debugging tool
1 | const axes = new THREE.AxesHepler(5) |
Materials, lights, and shadows
Light
加入光源
- spotLight 聚光灯
- spotLightHepler 聚光灯辅助线
1 | let spotLight = new THREE.SpotLight(0xaa00aa) |
Material
threeJs中有些材质是不受光线影响的,如MeshBasicMaterial
想要创建受光照作用的材质,可以使用其他材质,如:
- MeshLambertMaterial
- MeshPhongMaterial
Shadow
由于渲染shadow会耗费大量CPU资源,因此默认是disabled的,
需要三步开启shadow:
- 开启指定投射阴影物和被投射阴影物的阴影投射属性 castShadow/receiveShadow
1
2
3
4// 投射阴影物体
cube.castShadow = true
// 被投射阴影物体
plan.receiveShadow = true - 开启指定光源的阴影投射属性 castShadow
1
spotLight.castShadow = true
- 开启渲染器Renderer的阴影贴图shadowMap
1
renderer.shadowMap.enabled = true
Stats 性能检测插件
Stats能够检测当前屏幕的fps值
fps : frame per second
1 | import Stats from 'three/examples/jsm/libs/stats.module' |
Animations
requestAnimationFrame
1 | requestAnimationFrame(nextFrameFun) |
requestAnimationFrame相当于告诉浏览器绘制下一帧时调用的函数,
threeJs中的更新函数一般在requestAnimationFrame指定的函数中调用
1 | function animation(){ |
GUI
dat.gui
lil-gui提供快速编辑渲染参数的工具插件
Resize
resize
需要在window的resize事件时做下面两步
1 | window.addEventListener('resize',resize) |