Three.js解决方案
重要通知
。
基本概况
Three.js由来自西班牙巴塞罗那的Ricardo Cabello在2010四月于GitHub首次发布。同时贡献了包括基于 WebGL 的 3D 引擎 Three.js、js 性能监控工具 Stats.js、纹理生成工具 Texgen.js
技术文档:https://threejs.org/
中文文档:https://threejs.org/docs/index.html#manual/zh/introduction/Creating-a-scene
GitHub:https://github.com/mrdoob/three.js/
作者mrdoob主页:https://github.com/mrdoob
- Vue TresJS: https://tresjs.org/
相关类库
JavaScript 游戏引擎:https://impactjs.com/ https://github.com/phoboslab https://phoboslab.org/ 插值方法:http://paulbourke.net/miscellaneous/interpolation/
常见案例
参考游戏:http://hexgl.bkcore.com/play/ 用Three.js打造酷炫3D个人网站(含源码):https://juejin.cn/post/6985033373857579045 各种图形图案:https://threejs.org/examples/#webgl_buffergeometry_lines_indexed WebGL开发案例:http://www.tiyiweb.com/ littleworkshop(经典THREE 3D | 超级厉害的公司技术):https://www.littleworkshop.fr/ 高清城市系统:https://demos.littleworkshop.fr/demos/infinitown/ Three.js游戏案例:https://phoboslab.org/wipeout/ 书籍 Physically Based Rendering in Filament:https://google.github.io/filament/Filament.html 经典游戏实现案例:https://phoboslab.org/wipeout/ 日月星辰动态 | 元宇宙的入口 | 超级炫酷:https://www.nationalgeographic.com/science/graphics/cassini-saturn-nasa-3d-grand-tour
three.js后期之自定义shader通道实现扫光效果:https://www.cnblogs.com/eco-just/p/11667713.html 用three.js实现炫酷的城市扫光效果:https://blog.csdn.net/zhgu1992/article/details/104227100
GitHub:https://github.com/ma77os/InteractiveLandscape 示例:https://tympanus.net/Development/InteractiveLandscape/ 暮志未晚技术博客:https://www.wjceo.com/ 3D案例:https://2912401452.github.io/ VR看房:http://test.mangoya.cn/Aimee/DEMO/3Drotate/demo/Sphere.html 经典案例:https://threejs.org/examples/#webgl_helpers 郭隆邦:http://www.yanhuangxueyuan.com/ https://duoduoview.com/example/access/ 游戏:https://github.com/Kingles/gamelab.js WebGL中文网:http://www.hewebgl.com/
HexGL by BKcore:http://hexgl.bkcore.com/play/ https://codeartemis.github.io/ 使用THREE.js制作一款3D游戏:https://blog.csdn.net/qq_40748336/article/details/82946851 日环食大挑战:https://quincychen.cn/threejs-experience/ IFE-WebGL:https://husterxsp.github.io/IFE-WebGL/ 游戏案例:https://husterxsp.github.io/IFE-WebGL/task8/
坐标辅助线系统
坐标系
正面面对电脑屏幕
- X坐标:前后 | 正数-前 | 负数-后
- Y坐标:上下 | 正数-上 | 负数-下
- Z坐标:左右 | 正数-左 | 负数-右
坐标轴 | THREE.AxesHelper
作用:绘制模拟3个坐标轴的对象,红色代表 X 轴. 绿色代表 Y 轴. 蓝色代表 Z 轴.
const axesHelper = new THREE.AxesHelper(
size: Number // [可选] 表示三条坐标轴的绘制长度,默认为 1。
);
scene.add(axesHelper);
axesHelper.position.set(0, 0, 0); // 设置坐标轴辅助中心点,默认为场景中心
THREE.GridHelper | 坐标格辅助对象
作用:坐标格辅助对象,坐标格实际上是2维线数组。
const gridHelper = new THREE.GridHelper(
size: number, // 坐标格整体长宽尺寸大小,默认为 10。
divisions: Number, // 在坐标格整体长宽尺寸大小确定的基础上,设置坐标格的细分个数,默认为 10个。
colorCenterLine: Color, // 中线颜色. 值可以为 Color 类型, 16进制 和 CSS 颜色名. 默认为 0x444444
colorGrid: Color // 坐标格网格线颜色. 值可以为 Color 类型, 16进制 和 CSS 颜色名. 默认为 0x888888
)
scene.add(gridHelper);
gridHelper.position.set(0, 0, 0); // 设置坐标格辅助中心点,默认为场景中心
BoxHelper
基础函数
console.log(new THREE.Vector2( 0, 1 )); // {x: 0, y: 1}
console.log(new THREE.Vector3( 0, 1, 0 )); // {x: 0, y: 1, z: 0}
console.log(new THREE.Vector4( 0, 1, 0, 0 )); // {x: 0, y: 1, z: 0, w: 0}
内部工具函数
基础函数
console.log(new THREE.Color()); // {}
console.log(new THREE.Color( 0xff0000 )); // {r: 1, g: 0, b: 0}
console.log(new THREE.Color("rgb(255, 0, 0)")); // {r: 1, g: 0, b: 0}
console.log(new THREE.Color("rgb(100%, 0%, 0%)")); // {r: 1, g: 0, b: 0}
console.log(new THREE.Color( 'skyblue' )); // {r: 0.5294117647058824, g: 0.807843137254902, b: 0.9215686274509803}
console.log(new THREE.Color("hsl(0, 100%, 50%)")); // {r: 1, g: 0, b: 0}
console.log(new THREE.Color( 1, 0, 0 )); // {r: 1, g: 0, b: 0}
三维物体(Object3D)与组(Group)
组(THREE.Group):方便统一管理物体
const obejct = new THREE.Object3D();
obejct.add();
const group = new THREE.Group();
group.add( cubeA );
const mouse = new THREE.Vector2( 0, 1 ); // {x: 0, y: 1}
const a = new THREE.Vector3( 0, 1, 0 );
const a = new THREE.Vector4( 0, 1, 0, 0 );
const color = new THREE.Color(); // new THREE.Color( 0xff0000 ); | new THREE.Color("rgb(255, 0, 0)"); | new THREE.Color("rgb(100%, 0%, 0%)"); | new THREE.Color( 'skyblue' ); | new THREE.Color("hsl(0, 100%, 50%)");
渲染器Renderer
渲染器
CSS 2D渲染器(CSS2DRenderer) CSS 3D渲染器(CSS3DRenderer) SVG渲染器(SVGRenderer)
CSS 2D渲染器(CSS2DRenderer)
CSS 3D渲染器(CSS3DRenderer)
SVG渲染器(SVGRenderer)
代码示例
const RENDERER = new THREE.WebGLRenderer({ antialias: true }); //antialias:true 增加抗锯齿效果
RENDERER.setClearColor(new THREE.Color(0x000000), 1); // 设置窗口背景颜色为黑
RENDERER.setSize(window.innerWidth, window.innerHeight); // 设置窗口尺寸
RENDERER.setPixelRatio( window.devicePixelRatio ); // 设置设备像素比。通常用于避免HiDPI设备上绘图模糊
RENDERER.outputEncoding = THREE.sRGBEncoding;
RENDERER.toneMapping = THREE.ReinhardToneMapping;
RENDERER.shadowMap
RENDERER.
RENDERER.
RENDERER.
document.body.appendChild(RENDERER.domElement);
RENDERER.render(scene, camera);
自定义挂载canvas
var RENDERER = new THREE.WebGLRenderer({
canvas: document.getElementById('mainCanvas')
});
API属性与方法
场景Scene
SCENE.add(object1, object2, ..., objectn);
代码示例
SCENE.background = new THREE.Color( 0xff0000 ); // 设置背景
SCENE.background = new THREE.TextureLoader().load('/Reference/images/141_1443.jpg'); // 设置背景纹理
// 雾(Fog)
SCENE.fog = new THREE.Fog(0xf7d9aa, 100, 950);
SCENE.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
// 添加物体
scene.add(object);
scene.remove(object.uuid);
属性
scene.autoUpdate: Boolean // 默认值为true,若设置了这个值,则渲染器会检查每一帧是否需要更新场景及其中物体的矩阵。 当设为false时,你必须亲自手动维护场景中的矩阵。 scene.background : Object // Color(颜色) | 一个覆盖canvas的Texture(纹理)
缩放器:camera.position.z = 5;
雾(Fog)
雾-指数(FogExp2)
API属性与方法
uuid name type parent children up position rotation quaternion scale matrix matrixWorld matrixAutoUpdate matrixWorldNeedsUpdate layers visible castShadow receiveShadow frustumCulled renderOrder userData background environment fog overrideMaterial autoUpdate constructor isScene copy add remove toJSON dispose isObject3D onBeforeRender onAfterRender applyMatrix4 applyQuaternion setRotationFromAxisAngle setRotationFromEuler setRotationFromMatrix setRotationFromQuaternion rotateOnAxis rotateOnWorldAxis rotateX rotateY rotateZ translateOnAxis translateX translateY translateZ localToWorld worldToLocal lookAt attach getObjectById getObjectByName getObjectByProperty getWorldPosition getWorldQuaternion getWorldScale getWorldDirection raycast traverse traverseVisible traverseAncestors updateMatrix updateMatrixWorld updateWorldMatrix clone getChildByName renderDepth translate getWorldRotation applyMatrix addEventListener hasEventListener removeEventListener dispatchEvent
摄像机Camera
简介与核心思想
摄像机,即摄像机的空间位置、摄像机对焦的目标对象位置 [注意]:投影效果:主视图,俯视图,左视图
CAMERA.position
作用:设置相机位置,即相机要摆在哪里?
CAMERA.position.set(0, 0, 0);
CAMERA.position.x = value; | CAMERA.position.y = value; | CAMERA.position.z = value;
CAMERA.up | 相机相对于坐标系的摆放姿势
作用:相机相对于坐标系中场景的视野姿势。眼睛向上-(0,-1,0),眼睛向前-(1,0,0),眼睛向右-(0,0,-1),其他 [注意]:CAMERA.up必须放置在CAMERA.lookAt前面
CAMERA.up ( x : Float, y : Float, z : Float )
CAMERA.up.set(0, 0, 0); | CAMERA.up.x = | CAMERA.up.y = | CAMERA.up.z =
CAMERA.lookAt | 基准点 | 两点决定一条直线 | CAMERA.position与camera.lookAt决定了物体的成像规则 | 大小与形状
作用:声明相机拍摄方向(朝向),即相机拍摄时指向的中心点。例如我们看电脑是从屏幕外部向屏幕内部看 [注意]:可设置小范围THREE.GridHelper网格线看效果
CAMERA.lookAt ( x : Float, y : Float, z : Float )
CAMERA.lookAt(0, 0, 0);
---------------------------------------
透视投影 | 管中窥豹-视锥体 | 管的半径越大,豹越小;反之则越大
---------------------------------------
特征:用来模拟人眼所看到的景象,近大远小。 构造函数
new THREE.PerspectiveCamera(
fov : Number, // 摄像机视锥体垂直视野角度,值越大,物体在场景中的渲染视觉成像越小。值范围0 ~ 180 | 类似于人的眼睛睁开视野范围,值越大,物体对象越小。
aspect : Number, // 摄像机视锥体长宽比,实际画布的宽/高比
near : Number, // 摄像机视锥体近端面 | 即摄像机镜头的拍照视野的有效开始点 | 一般就是镜头位置
far : Number // 摄像机视锥体远端面,该值必须大于near值,可以无限大。| 镜头能够覆盖的有效范围 | 约束视野的范围,小于空间的物体位置时,就会导致物体失去视野呈现
);
默认值
var CAMERA = new THREE.PerspectiveCamera( fov = 50, aspect = 1, near = 0.1, far = 2000 );
代码示例 CAMERA.position.set(x, y, z); // z:near < z < far
特别注意
在透视投影机制上,camera.position.z值越大,物体成像尺寸越小。
---------------------------------------
正交投影 | THREE.OrthographicCamera
---------------------------------------
重点:left、right、top、bottom,构成了一个长方体管子,通过这个管子窥探画布上的成像 对于制图、建模软件通常使用正交投影,这样不会因为投影而改变物体比例。 特征:场景中的物体大小远近都相同 构造函数
new THREE.OrthographicCamera(
left : Number, // 摄像机视锥体左侧面
right : Number, // 摄像机视锥体右侧面,不能大于left
top : Number, // 摄像机视锥体上侧面
bottom : Number, // 摄像机视锥体下侧面,不能大于top
near : Number, // 摄像机视锥体近端面
far : Number // 摄像机视锥体远端面
);
默认值 var CAMERA = new THREE.OrthographicCamera(l, r, t, b, 0.1, 2000); 代码示例
代码示例
// 当改变fov、aspect、near、far后,需要重新计算投影矩阵
CAMERA.aspect = window.innerWidth / window.innerHeight;
CAMERA.updateProjectionMatrix(); // 更新摄像机投影矩阵。在任何参数被改变以后必须被调用。
CAMERA.visible = true;
CAMERA.castShadow
CAMERA.receiveShadow
ArrayCamera | 摄像机阵列(ArrayCamera)
功效:ArrayCamera 用于更加高效地使用一组已经预定义的摄像机来渲染一个场景。这将能够更好地提升VR场景的渲染性能。
Camera
CubeCamera
OrthographicCamera
PerspectiveCamera
StereoCamera
###################################################################################################
基类
###################################################################################################
API属性与方法
uuid name type parent children up position rotation quaternion scale matrix matrixWorld matrixAutoUpdate matrixWorldNeedsUpdate layers visible castShadow receiveShadow frustumCulled renderOrder userData matrixWorldInverse projectionMatrix projectionMatrixInverse fov zoom near far focus aspect view filmGauge filmOffset constructor isPerspectiveCamera copy setFocalLength getFocalLength getEffectiveFOV getFilmWidth getFilmHeight setViewOffset clearViewOffset updateProjectionMatrix toJSON setLens isCamera getWorldDirection updateMatrixWorld updateWorldMatrix clone isObject3D onBeforeRender onAfterRender applyMatrix4 applyQuaternion setRotationFromAxisAngle setRotationFromEuler setRotationFromMatrix setRotationFromQuaternion rotateOnAxis rotateOnWorldAxis rotateX rotateY rotateZ translateOnAxis translateX translateY translateZ localToWorld worldToLocal lookAt add remove attach getObjectById getObjectByName getObjectByProperty getWorldPosition getWorldQuaternion getWorldScale raycast traverse traverseVisible traverseAncestors updateMatrix getChildByName renderDepth translate getWorldRotation applyMatrix addEventListener hasEventListener removeEventListener dispatchEvent
控制器Controls
---------------------------------------
轨道控制器(OrbitControls)
---------------------------------------
import { OrbitControls } from '/Visual/ThreeJS/source/controls/OrbitControls.js';
orbitControls.enableZoom = true; // 是否可以缩放
orbitControls.enablePan = true; // 是否开启右键拖拽
orbitControls.maxPolarAngle = Math.PI/2; // 能够垂直旋转的角度的上限,范围是0到Math.PI,其默认值为Math.PI。
controls.listenToKeyEvents( window ); // 为指定的DOM元素添加按键监听。推荐将window作为指定的DOM元素。
orbitControls.screenSpacePanning = false; // 定义当平移的时候摄像机的位置将如何移动。
RENDERER.setAnimationLoop(() => {
orbitControls.update();
RENDERER.render( SCENE, CAMERA );
});
---------------------------------------
拖放控制器(DragControls)
---------------------------------------
import { DragControls } from '/Visual/ThreeJS/source/controls/DragControls.js';
---------------------------------------
第一人称控制器(FirstPersonControls)
---------------------------------------
import { FirstPersonControl } from '/Visual/ThreeJS/source/controls/FirstPersonControls.js';
---------------------------------------
飞行控制器(FlyControls)
---------------------------------------
import { FlyControls } from '/Visual/ThreeJS/source/controls/FlyControls.js';
const controls = new FlyControls( CAMERA, RENDERER.domElement );
controls.autoForward = false; // 若该值设为true,初始变换后,摄像机将自动向前移动(且不会停止)。默认为false。
controls.dragToLook = false; // 若该值设为true,你将只能通过执行拖拽交互来环视四周。默认为false。
controls.movementSpeed = 1; // 移动速度,默认为1。
controls.rollSpeed = 0.005; // 旋转速度。默认为0.005。
controls.dispose(); // 若不再需要该控制器,则应当调用此函数。
controls.update(); // 更新控制器,常被用在动画循环中。
// 监听变化
controls.change = function {};
// 调度机制
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame( animate );
const delta = clock.getDelta();
flyControls.update(delta);
RENDERER.render( SCENE, CAMERA );
}
animate();
---------------------------------------
指针锁定控制器(PointerLockControls)
场景:射击游戏
---------------------------------------
import { PointerLockControls } from '/Visual/ThreeJS/source/controls/PointerLockControls.js';
const controls = new PointerLockControls(CAMERA, document.body);
---------------------------------------
轨迹球控制器(TrackballControls)
---------------------------------------
import { TrackballControls } from '/Visual/ThreeJS/source/controls/TrackballControls.js';
---------------------------------------
变换控制器(TransformControls)
---------------------------------------
import { TransformControls } from '/Visual/ThreeJS/source/controls/TransformControls.js';
---------------------------------------
(ArcballControls)
---------------------------------------
import { ArcballControls } from '/Visual/ThreeJS/source/controls/ArcballControls.js';
灯光模型Light
注意事项 | 光照依赖材质类型,光照只有在特定材质类型的基础上才能产生效果 | 注意THREE.PlaneGeometry问题,[单面] [垂直]等问题
[注意] 投影很复杂,运用之前请仔细参考 /Visual/ThreeJS/Example/Light.html
[投影] 采用[THREE.ShadowMaterial()],除了可以投影,其他的都是透明,体验很好
开启渲染器阴影效果:renderer.shadowMap.enabled = true; 开启物体投影属性:[object].castShadow = true; 开启光源阴影属性:[light].castShadow = true; 开启接收阴影:[name].receiveShadow = true; 注意光源的distance值,该值决定了投影的问题。 前置:阴影呈现载体,一般使用 THREE.PlaneGeometry 绘制 材质要求:必须能够产生光照反应的材质,否则无效。
基本概念
局部光照:通过计算对象表面和射向它的光线之间的交点来实现表面绘制的模型 全局光照:为了生成更加真实的光照效果,必须考虑从其他对象反射出来的光线,这些反射光线也会照射到物体上并对它们表面的明暗效果产生贡献。
代码示例
---------------------------------------
平行光(DirectionalLight)| DirectionalLightHelper | [太阳光] [投影]
材料(Material):[不限]
[注意] 需要投影则配置shadow参数
---------------------------------------
功效:平行光是沿着特定方向发射的光。这种光的表现像是无限远,从它发出的光线都是平行的。常常用平行光来模拟太阳光 的效果; 太阳足够远,因此我们可以认为太阳的位置是无限远,所以我们认为从太阳发出的光线也都是平行的。
构造函数
new THREE.DirectionalLight(
color : Integer, // [可选] 16进制表示光的颜色。 缺省值为 0xffffff (白色)。
intensity : Float // [可选] 光照的强度。缺省值为1。
)
代码示例
const light = new THREE.DirectionalLight( 0xFFFFFF, 1 );
light.castShadow = true;
SCENE.add( light );
// 追踪到目标对象,即平行光会一直追踪目标对象
const object = new THREE.Object3D();
SCENE.add(object);
light.target = object;
// 设置计算阴影的区域
light.shadow.camera.near = 0.5;
light.shadow.camera.far = 300;
light.shadow.camera.left = -50;
light.shadow.camera.right = 50;
light.shadow.camera.top = 200;
light.shadow.camera.bottom = -100;
// 辅助线
const helper = new THREE.DirectionalLightHelper( light, 5 );
SCENE.add( helper );
---------------------------------------
点光源(PointLight)| PointLightHelper | [灯泡] [投影]
材料(Material):[不限]
[注意] 需要light.add(target); 添加目标对象才能显著有效
---------------------------------------
功效:从一个点向各个方向发射的光源。一个常见的例子是模拟一个灯泡发出的光。
构造函数
new THREE.PointLight(
color : Integer, // [可选] 十六进制光照颜色。 缺省值 0xffffff (白色)。
intensity : Float, // [可选] 光照强度。 缺省值 1。
distance : Number, // [可选] 这个距离表示从光源到光照强度为0的位置。 当设置为0时,光永远不会消失(距离无穷大)。缺省值 0.
decay : Float // [可选] 沿着光照距离的衰退量。缺省值 1。 在 physically correct 模式中,decay = 2。
)
代码示例
const light = new THREE.PointLight( 0xffffff, 1 );
light.position.set( 0, 0, 0 );
light.castShadow = true;
SCENE.add( light );
// 辅助线
const pointLightHelper = new THREE.PointLightHelper( pointLight, 1 );
SCENE.add( pointLightHelper );
---------------------------------------
聚光灯(SpotLight) | SpotLightHelper [投影]
材料(Material):MeshLambertMaterial | MeshPhongMaterial
---------------------------------------
功效:光线从一个点沿一个方向射出,随着光线照射的变远,光线圆锥体的尺寸也逐渐增大。
使用经验
[注意]:
构造函数
new THREE.SpotLight(
color : Integer, // [可选] 十六进制光照颜色。 缺省值 0xffffff (白色)。
intensity : Float, // [可选] 光照强度。 缺省值 1。
distance : Float, // [可选] 从光源发出光的最大距离,其强度根据光源的距离线性衰减。
angle : Radians, // [可选] 光线散射角度,最大为Math.PI/2。
penumbra : Float, // [可选] 聚光锥的半影衰减百分比。在0和1之间的值。默认为0。
decay : Float // [可选] 沿着光照距离的衰减量。
)
代码示例
const light = new THREE.SpotLight( 0xffffff );
light.position.set( 100, 1000, 100 );
light.angle = Math.PI /6
light.castShadow = true;
SCENE.add( light );
// 阴影区域
light.shadow.camera.near = 1
light.shadow.camera.far = 300
light.shadow.camera.fov = 20
// 辅助线
const lightHelper = new THREE.SpotLightHelper( light );
SCENE.add( lightHelper );
---------------------------------------
环境光(AmbientLight)| [天空]
---------------------------------------
功效:环境光会均匀的照亮场景中的所有物体。
使用经验
[注意]:环境光不能用来投射阴影,因为它没有方向。
构造函数
new THREE.AmbientLight(
color : Integer, // [可选] 颜色的rgb数值。缺省值为 0xffffff。
intensity : Float // [可选] 光照的强度。缺省值为 1。
)
代码示例
const light = new THREE.AmbientLight( 0xffffff );
SCENE.add( light );
---------------------------------------
半球光(HemisphereLight)| HemisphereLightHelper
---------------------------------------
功效:光源直接放置于场景之上,光照颜色从天空光线颜色渐变到地面光线颜色。
使用经验
[注意]:半球光不能投射阴影。
构造函数
new THREE.HemisphereLight(
skyColor : Integer, // [可选] 天空中发出光线的颜色。 缺省值 0xffffff。
groundColor : Integer, // [可选] 地面发出光线的颜色。 缺省值 0xffffff。
intensity : Float // [可选] 光照强度。 缺省值 1。
)
代码示例
const light = new THREE.HemisphereLight( 0xffffff, 0xff0000, 1 );
light.position.set( 100, 1000, 100 );
SCENE.add( light );
// 辅助线
const lightHelper = new THREE.HemisphereLightHelper( light, 5 );
SCENE.add( lightHelper );
---------------------------------------
平面光光源(RectAreaLight)| RectAreaLightHelper
[材料(Material)]:支持MeshStandardMaterial | MeshPhysicalMaterial
---------------------------------------
功效:平面光光源从一个矩形平面上均匀地发射光线。这种光源可以用来模拟像明亮的窗户或者条状灯光光源。
使用经验
[注意]:光源有效距离,如果太远则失效。 [注意]:不支持阴影。 你必须在你的场景中加入 RectAreaLightUniformsLib ,并调用init()。
构造函数
new THREE.RectAreaLight(
color : Integer, // [可选] 十六进制数字表示的光照颜色。缺省值为 0xffffff (白色)
intensity : Float, // [可选] 光源强度/亮度 。缺省值为 1。
width : Float, // [可选] 光源宽度。缺省值为 10。
height : Float // [可选] 光源高度。缺省值为 10。
)
代码示例
import { RectAreaLightUniformsLib } from '/Visual/ThreeJS/source/lights/RectAreaLightUniformsLib.js';
import { RectAreaLightHelper } from '/Visual/ThreeJS/source/helpers/RectAreaLightHelper.js';
RectAreaLightUniformsLib.init();
const light = new THREE.RectAreaLight( 0xffffff, 1, 10, 10 );
light.position.set( 5, 5, 0 );
light.lookAt( 0, 0, 0 );
SCENE.add( light );
const lightHelper = new THREE.RectAreaLightHelper( light );
SCENE.add( lightHelper );
---------------------------------------
环境光探针(AmbientLightProbe)
---------------------------------------
功效:
构造函数
new THREE.AmbientLightProbe(
color : Color, // [可选] 一个表示颜色的 Color 的实例、字符串或数字。
intensity : Float // [可选] 光照探针强度的数值。默认值为1。
)
代码示例
---------------------------------------
半球光探针(HemisphereLightProbe)
---------------------------------------
功效:
构造函数
new THREE.HemisphereLight(
skyColor : Integer, // [可选] 一个表示颜色的 Color 的实例、字符串或数字。
groundColor : Integer, // [可选] 一个表示颜色的 Color 的实例、字符串或数字。
intensity : Float // [可选] 光照探针强度的数值。默认值为1。
)
代码示例
---------------------------------------
镜头光晕(LensFlare)
---------------------------------------
功效:
构造函数
代码示例
---------------------------------------
---------------------------------------
功效:
构造函数
代码示例
###################################################################################################
基类:Light
###################################################################################################
API属性与方法
材质Material
基础变量 | new THREE.MeshNormalMaterial()
THREE.DoubleSide
---------------------------------------
基础线条材质(LineBasicMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
虚线材质(LineDashedMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
基础网格材质(MeshBasicMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
深度网格材质(MeshDepthMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
MeshDistanceMaterial
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
Lambert网格材质(MeshLambertMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
MeshMatcapMaterial
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
法线网格材质(MeshNormalMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
Phong网格材质(MeshPhongMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
物理网格材质(MeshPhysicalMaterial)
---------------------------------------
---------------------------------------
标准网格材质(MeshStandardMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
MeshToonMaterial
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
点材质(PointsMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
原始着色器材质(RawShaderMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
着色器材质(ShaderMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
阴影材质(ShadowMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
点精灵材质(SpriteMaterial)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
###################################################################################################
基类:Material
###################################################################################################
API属性与方法
线Line
代码示例
// 线条件绘制
const points = ...;
const geometry = new THREE.BufferGeometry().setFromPoints( points );
const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
const line = new THREE.Line( geometry, material );
SCENE.add( line );
二次贝塞尔曲线
const path = new THREE.Path();
path.lineTo( 0, 0 );
path.quadraticCurveTo( 0, 10, 10, 10 );
const points = path.getPoints();
三维样条曲线
export function CatmullRomCurve3() {
const curve = new THREE.CatmullRomCurve3( [
new THREE.Vector3( -10, 0, 10 ),
new THREE.Vector3( -5, 5, 5 ),
new THREE.Vector3( 0, 0, 0 ),
new THREE.Vector3( 5, -5, 5 ),
new THREE.Vector3( 10, 0, 10 )
] );
const points = curve.getPoints( 50 );
const geometry = new THREE.BufferGeometry().setFromPoints( points );
const material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
const line = new THREE.Line( geometry, material );
SCENE.add(line);
}
椭圆 | 圆 | 弧线(ArcCurve)
export function EllipseCurve() {
const curve = new THREE.EllipseCurve(
0, 0, // ax, aY
10, 10, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0 // aRotation
);
const points = curve.getPoints( 50 );
const geometry = new THREE.BufferGeometry().setFromPoints( points );
const material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
const line = new THREE.Line( geometry, material );
SCENE.add(line);
}
二维三次贝塞尔曲线
export function CubicBezierCurve() {
const curve = new THREE.CubicBezierCurve(
new THREE.Vector2( -10, 0 ),
new THREE.Vector2( -5, 15 ),
new THREE.Vector2( 20, 15 ),
new THREE.Vector2( 10, 0 )
);
const points = curve.getPoints( 50 );
const geometry = new THREE.BufferGeometry().setFromPoints( points );
const material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
const line = new THREE.Line( geometry, material );
SCENE.add(line);
}
三维三次贝塞尔曲线
export function CubicBezierCurve3() {
const curve = new THREE.CubicBezierCurve3(
new THREE.Vector3( -10, 0, 0 ),
new THREE.Vector3( -5, 15, 0 ),
new THREE.Vector3( 20, 15, 0 ),
new THREE.Vector3( 10, 0, 0 )
);
const points = curve.getPoints( 50 );
const geometry = new THREE.BufferGeometry().setFromPoints( points );
const material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
const line = new THREE.Line( geometry, material );
SCENE.add(line);
}
二维二次贝塞尔曲线
export function QuadraticBezierCurve() {
const curve = new THREE.QuadraticBezierCurve(
new THREE.Vector2( -10, 0 ),
new THREE.Vector2( 20, 15 ),
new THREE.Vector2( 10, 0 )
);
const points = curve.getPoints( 50 );
const geometry = new THREE.BufferGeometry().setFromPoints( points );
const material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
const line = new THREE.Line( geometry, material );
SCENE.add(line);
}
三维二次贝塞尔曲线
export function QuadraticBezierCurve3() {
const curve = new THREE.QuadraticBezierCurve3(
new THREE.Vector3( -10, 0, 0 ),
new THREE.Vector3( 20, 15, 0 ),
new THREE.Vector3( 10, 0, 0 )
);
const points = curve.getPoints( 50 );
const geometry = new THREE.BufferGeometry().setFromPoints( points );
const material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
const line = new THREE.Line( geometry, material );
SCENE.add(line);
}
纹理Texture
代码示例
const texture = new THREE.TextureLoader().load( "/Visual/ThreeJS/Example/STATIC/images/textures/brick_roughness.jpg" );
texture.minFilter = THREE.NearestFilter;
texture.magFilter = THREE.NearestFilter;
texture.anisotropy = 1;
texture.generateMipmaps = false;
texture.needsUpdate = true; // 如果更改了图像,画布,视频和数据纹理,则需要设置更新纹理,渲染对象就会自动更新。
const cube = new THREE.Mesh(
new THREE.BoxGeometry( 100, 100, 100 ),
new THREE.MeshBasicMaterial({ map: texture })
);
Scene.add( cube );
THREE.ImageUtils.loadTexture已废弃
THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.
---------------------------------------
Canvas纹理(CanvasTexture)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
压缩的纹理(CompressedTexture
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
立方纹理(CubeTexture)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
DataTexture
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
DataTexture2DArray
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
DataTexture3D
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
深度纹理(DepthTexture)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
FramebufferTexture
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
---------------------------------------
纹理(Texture)
---------------------------------------
基础知识
[注意]:
构造函数
代码演示
###################################################################################################
基类:Texture
###################################################################################################
API属性与方法
几何体Geometry
简介
BufferGeometry:是面片、线或点几何体的有效表述。包括顶点位置,面片索引、法相量、颜色值、UV 坐标和自定义缓存属性值。使用 BufferGeometry 可以有效减少向 GPU 传输上述数据所需的开销。 BufferAttribute:用于存储与BufferGeometry相关联的 attribute(例如顶点位置向量,面片索引,法向量,颜色值,UV坐标以及任何自定义 attribute )。 利用 BufferAttribute,可以更高效的向GPU传递数据。
基类 | BufferGeometry
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array( [
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, -1.0, 1.0
] );
geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
geometry.applyMatrix4( new THREE.Matrix4().makeTranslation( 0, 0.5, 0 ) ); // 修改图形的基础坐标
geometry.scale(200, 1000, 500);
---------------------------------------
立方缓冲几何体(BoxGeometry)| 正方体•长方体
---------------------------------------
构造函数
new THREE.BoxGeometry(
width : Float, // X轴上面的宽度,默认值为1。
height : Float, // Y轴上面的高度,默认值为1。
depth : Float, // Z轴上面的深度,默认值为1。
widthSegments : Integer, // (可选)宽度的分段数,默认值是1。
heightSegments : Integer, // (可选)宽度的分段数,默认值是1。
depthSegments : Integer // (可选)宽度的分段数,默认值是1。
)
代码示例 | 正方体
const mesh = new THREE.Mesh(
new THREE.BoxGeometry( 100, 100, 100 ), // new THREE.BoxGeometry( 100, 100, 300 ); // 长方体
new THREE.MeshNormalMaterial()
);
mesh.position.set(0, 100, 0);
scene.add( mesh );
---------------------------------------
圆形缓冲几何体(CircleGeometry)| 圆形•散形•多边形•正方形•长方形•三角形
---------------------------------------
构造函数
new THREE.CircleGeometry(
radius : Float, // 圆形的半径,默认值为1
segments : Integer, // 分段(三角面)的数量,最小值为3,默认值为8。
thetaStart : Float, // 第一个分段的起始角度,默认为0。
thetaLength : Float // 圆形扇区的中心角,通常被称为“θ”(西塔)。默认值是2*Pi,这使其成为一个完整的圆。
)
代码示例 | 多边形 | 圆形 | 三角形 | 自由设置边数就OK
const geometryMesh = new THREE.Mesh(
new THREE.CircleGeometry( 30, 1000 ),
new THREE.MeshNormalMaterial()
);
geometryMesh.rotation.x = -0.5 * Math.PI;
geometryMesh.position.set(0, 10, 0);
scene.add( geometryMesh );
---------------------------------------
圆锥缓冲几何体(ConeGeometry)| 圆锥体
---------------------------------------
构造函数
new THREE.ConeGeometry(
radius : Float, // 圆锥底部的半径,默认值为1。
height : Float, // 圆锥的高度,默认值为1。
radialSegments : Integer, // 圆锥侧面周围的分段数,默认为8。
heightSegments : Integer, // 圆锥侧面沿着其高度的分段数,默认值为1。
openEnded : Boolean, // 一个Boolean值,指明该圆锥的底面是开放的还是封顶的。默认值为false,即其底面默认是封顶的。
thetaStart : Float, // 第一个分段的起始角度,默认为0。
thetaLength : Float // 圆锥底面圆扇区的中心角,通常被称为“θ”(西塔)。默认值是2*Pi,这使其成为一个完整的圆锥。
)
代码示例 | 圆底 | 多边底
const geometryMesh = new THREE.Mesh(
new THREE.ConeGeometry( 100, 200, 10 ),
new THREE.MeshNormalMaterial()
);
geometryMesh.position.set(0, 100, 0);
scene.add( geometryMesh );
---------------------------------------
圆柱缓冲几何体(CylinderGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
十二面缓冲几何体(DodecahedronGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
边缘几何体(EdgesGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
挤压缓冲几何体(ExtrudeGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
二十面缓冲几何体(IcosahedronGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
车削缓冲几何体(LatheGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
八面缓冲几何体(OctahedronGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
平面缓冲几何体(PlaneGeometry)
---------------------------------------
构造函数
new THREE.PlaneGeometry(
width : Float,
height : Float,
widthSegments : Integer,
heightSegments : Integer
)
代码示例
const planeMesh = new THREE.Mesh(
new THREE.PlaneGeometry( 400, 400, 32 ),
new THREE.MeshNormalMaterial()
);
planeMesh.rotation.x = -0.5 * Math.PI;
planeMesh.receiveShadow = true;
planeMesh.position.set(0, 10, 0);
scene.add( planeMesh );
---------------------------------------
多面缓冲几何体(PolyhedronGeometry)
---------------------------------------
多面体在三维空间中具有一些平面的立体图形。这个类将一个顶点数组投射到一个球面上,之后将它们细分为所需的细节级别。
构造函数
new THREE.PolyhedronGeometry(
vertices : Array, // 一个顶点Array(数组):[1,1,1, -1,-1,-1, ... ]。
indices : Array, // 一个构成面的索引Array(数组), [0,1,2, 2,3,0, ... ]。
radius : Float, // 最终形状的半径。
detail : Integer // 将对这个几何体细分多少个级别。细节越多,形状就越平滑。
)
代码示例
---------------------------------------
圆环缓冲几何体(RingGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
形状缓冲几何体(ShapeGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
球缓冲几何体(SphereGeometry)
---------------------------------------
构造函数
new THREE.SphereGeometry(
radius : Float, // 球体半径,默认为1。
widthSegments : Integer, // 水平分段数(沿着经线分段),最小值为3,默认值为8。
heightSegments : Integer, // 垂直分段数(沿着纬线分段),最小值为2,默认值为6。
phiStart : Float, // 指定水平(经线)起始角度,默认值为0。
phiLength : Float, // 指定水平(经线)扫描角度的大小,默认值为 Math.PI * 2。
thetaStart : Float, // 指定垂直(纬线)起始角度,默认值为0。
thetaLength : Float // 指定垂直(纬线)扫描角度大小,默认值为 Math.PI。
)
代码示例
---------------------------------------
四面缓冲几何体(TetrahedronGeometry)| 四面体
---------------------------------------
构造函数
new THREE.TetrahedronGeometry(
radius : Float, // 四面体的半径,默认值为1。
detail : Integer // 默认值为0。将这个值设为一个大于0的数将会为它增加一些顶点,使其不再是一个四面体。
)
代码示例
const geometryMesh = new THREE.Mesh(
new THREE.TetrahedronGeometry( 50, 0 ),
new THREE.MeshNormalMaterial()
);
geometryMesh.position.set(0, 100, 0);
scene.add( geometryMesh );
---------------------------------------
圆环缓冲几何体(TorusGeometry)
---------------------------------------
构造函数
new THREE.TorusGeometry(
radius : Float, // 圆环的半径,从圆环的中心到管道(横截面)的中心。默认值是1。
tube : Float, // 管道的半径,默认值为0.4。
radialSegments : Integer, // 圆环的分段数,默认值为8。
tubularSegments : Integer, // 管道的分段数,默认值为6。
arc : Float // 圆环的圆心角(单位是弧度),默认值为Math.PI * 2。
)
代码示例
const torus = new THREE.Mesh(
new THREE.TorusGeometry( 50, 15, 16, 100 ),
new THREE.MeshNormalMaterial()
);
scene.add( torus );
---------------------------------------
圆环缓冲扭结几何体(TorusKnotGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
管道缓冲几何体(TubeGeometry)
---------------------------------------
构造函数
代码示例
---------------------------------------
网格几何体(WireframeGeometry)
---------------------------------------
作用:用作一个辅助物体,来对一个geometry以线框的形式进行查看。
构造函数
new THREE.WireframeGeometry(
geometry : BufferGeometry // 几何体对象
)
代码示例
const line = new THREE.LineSegments(
new THREE.WireframeGeometry(
new THREE.SphereGeometry( 100, 100, 100 )
)
);
line.material.depthTest = false;
line.material.opacity = 0.25;
line.material.transparent = true;
scene.add( line );
###################################################################################################
经典图形示例
###################################################################################################
创建三角形
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array( [
-10, 0, 0,
10, 0, 0,
10, 20, 0,
] );
geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
const mesh = new THREE.Mesh( geometry, material );
scene.add(mesh);
凸包几何体(ConvexGeometry)
ConvexGeometry 可被用于为传入的一组点生成凸包。 该任务的平均时间复杂度被认为是O(nlog(n))
代码示例
import { ConvexGeometry } from '/Visual/ThreeJS/source/examples/jsm/geometries/ConvexGeometry.js';
const points = [];
points.push(new THREE.Vector3( 0, 0, 0 ));
points.push(new THREE.Vector3( 50, 0, 0 ));
points.push(new THREE.Vector3( 50, 50, 0 ));
points.push(new THREE.Vector3( 0, 50, 0 ));
points.push(new THREE.Vector3( 0, 50, 100 ));
const geometry = new ConvexGeometry( points );
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
###################################################################################################
基类:BufferGeometry
###################################################################################################
API属性与方法
动画Animation
动画思想
更新场景与更新相机视野范围目标 利用三轴坐标的变换来实现。
动画示例
淡入淡出、缩放、位移、旋转等动画
代码示例
requestAnimationFrame(function animate() {
.rotation.x += 0.3;
RENDERER.render( SCENE, CAMERA );
requestAnimationFrame(loop);
});
代替requestAnimationFrame
RENDERER.setAnimationLoop( () => {
RENDERER.render( SCENE, CAMERA );
} );
GSAP
相机动画 | 转场动画
import { TWEEN } from '/Animate/tweenJS/dist/tween.module.min.js';
const startState = CAMERA.position || { x: 0, y: 0, z: 1000 };
const endState = { x: startState.x, y: startState.y, z: ~startState.z };
const duration = 5000;
const delay = 2000;
const tween = new TWEEN.Tween(startState)
.to(endState, duration)
.delay(delay)
.easing(TWEEN.Easing.Quadratic.Out)
.onUpdate(() => {
CAMERA.position.z = startState.z;
})
.start();
RENDERER.setAnimationLoop(() => {
TWEEN.update();
RENDERER.render( SCENE, CAMERA );
});
加载器
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { } from '/Visual/ThreeJS/source/loaders/.js';
import { OBJLoader } from '/Visual/ThreeJS/source/loaders/OBJLoader.js';
import { PCDLoader } from '/Visual/ThreeJS/source/loaders/PCDLoader.js';
import { PDBLoader } from '/Visual/ThreeJS/source/loaders/PDBLoader.js';
import { PLYLoader } from '/Visual/ThreeJS/source/loaders/PLYLoader.js';
import { PRWMLoader } from '/Visual/ThreeJS/source/loaders/PRWMLoader.js';
import { PVRLoader } from '/Visual/ThreeJS/source/loaders/PVRLoader.js';
import { RGBELoader } from '/Visual/ThreeJS/source/loaders/RGBELoader.js';
import { STLLoader } from '/Visual/ThreeJS/source/loaders/STLLoader.js';
import { SVGLoader } from '/Visual/ThreeJS/source/loaders/SVGLoader.js';
import { TDSLoader } from '/Visual/ThreeJS/source/loaders/TDSLoader.js';
import { TGALoader } from '/Visual/ThreeJS/source/loaders/TGALoader.js';
import { TiltLoader } from '/Visual/ThreeJS/source/loaders/TiltLoader.js';
import { TTFLoader } from '/Visual/ThreeJS/source/loaders/TTFLoader.js';
import { VOXLoader } from '/Visual/ThreeJS/source/loaders/VOXLoader.js';
import { VRMLLoader } from '/Visual/ThreeJS/source/loaders/VRMLLoader.js';
import { VRMLoader } from '/Visual/ThreeJS/source/loaders/VRMLoader.js';
import { VTKLoader } from '/Visual/ThreeJS/source/loaders/VTKLoader.js';
import { XYZLoader } from '/Visual/ThreeJS/source/loaders/XYZLoader.js';
多媒体资源
图片(Image)
音频(Audio)
export function AudioStructure() {
const listener = new THREE.AudioListener();
CAMERA.add( listener );
// create a global audio source
const sound = new THREE.Audio( listener );
// load a sound and set it as the Audio object's buffer
const audioLoader = new THREE.AudioLoader();
audioLoader.load( '/Reference/audio/module.mp3', function( buffer ) {
sound.setBuffer( buffer );
sound.setLoop( true );
sound.setVolume( 0.5 );
});
document.addEventListener('click', function() {
if (sound.isPlaying) {
sound.pause();
return;
}
sound.play();
}, false);
}
视频(Video)
视频纹理
案例:https://github.com/mrdoob/three.js/blob/master/examples/webgl_materials_video.html
https://threejs.org/examples/#webgl_materials_video
代码示例
import { ReaderVideoData } from '/public/module/video.js';
import { fetchFile } from '/public/file/file.js';
import { GeometryStructure } from '/Visual/ThreeJS/Example/Geometries/index.js';
export async function VideoStructure() {
const path = await fetchFile('https://test.ysunlight.com/Reference/video/Format/video.mp4');
const video = await ReaderVideoData(path, 'video/mp4');
video.loop = true;
const texture = new THREE.VideoTexture( video );
GeometryStructure({
material: new THREE.MeshLambertMaterial( { color: 0xffffff, map: texture } )
});
document.addEventListener('click', function() {
if (!video.paused) {
video.pause();
return;
}
video.play();
}, false);
}
效果合成器(EffectComposer)
滤镜与效果 效果合成器,即类似于Gulp工作流程一样,通过EffectComposer声明一个渲染管道,往管道中添加不同的效果,最后合成绘制到屏幕上。 这些效果包括:增强光效、滤镜等各种变换。
代码示例
const composer = new EffectComposer( RENDERER ); // 创建合成器
composer.setPixelRatio( window.devicePixelRatio );
composer.setSize( window.innerWidth, window.innerHeight );
/**
* 配置后期处理过程链
*
*/
// 将渲染好的场景作为输入来提供给下一个后期处理步骤
const renderPass = new RenderPass( SCENE, CAMERA ); // 渲染通道
composer.addPass(renderPass);
// 描边高亮
const outlinePass = new THREE.OutlinePass(new THREE.Vector2(widnow.innerWidth, window.innerHeight), SCENE, CAMERA);
composer.addPass(outlinePass);
// 故障效果
glitchPass = new THREE.GlitchPass();
glitchPass.renderToScreen = true;
composer.addPass( glitchPass );
//
const lutPass = new LUTPass();
composer.addPass( lutPass );
/**
* 自定义后期处理着色器
*
*/
const copyPass = new ShaderPass( CopyShader );
copyPass.renderToScreen = true; // 输出当前内容
composer.addPass(copyPass); // 输出到屏幕
RENDERER.setAnimationLoop(() => {
orbitControls.update();
RENDERER.render( SCENE, CAMERA );
});
代码示例
import { EffectComposer } from '/Visual/ThreeJS/source/postprocessing/EffectComposer.js'; // 效果合成器
import { AdaptiveToneMappingPass } from '/Visual/ThreeJS/source/postprocessing/AdaptiveToneMappingPass.js'; //
import { AfterimagePass } from '/Visual/ThreeJS/source/postprocessing/AfterimagePass.js'; //
import { BloomPass } from '/Visual/ThreeJS/source/postprocessing/BloomPass.js'; // 增强场景中的亮度
import { BokehPass } from '/Visual/ThreeJS/source/postprocessing/BokehPass.js'; //
import { ClearPass } from '/Visual/ThreeJS/source/postprocessing/ClearPass.js'; //
import { CubeTexturePass } from '/Visual/ThreeJS/source/postprocessing/CubeTexturePass.js'; //
import { DotScreenPass } from '/Visual/ThreeJS/source/postprocessing/DotScreenPass.js'; // 将原始图片输出为灰度点集
import { FilmPass } from '/Visual/ThreeJS/source/postprocessing/FilmPass.js'; // 使用扫描线和失真来模拟电视屏幕效果
import { GlitchPass } from '/Visual/ThreeJS/source/postprocessing/GlitchPass.js'; // 随机在屏幕上显示电脉冲
import { HalftonePass } from '/Visual/ThreeJS/source/postprocessing/HalftonePass.js'; //
import { LUTPass } from '/Visual/ThreeJS/source/postprocessing/LUTPass.js'; //
import { MaskPass } from '/Visual/ThreeJS/source/postprocessing/MaskPass.js'; // 在当前图片上添加掩码,后续的通道只会影响掩码区域
import { OutlinePass } from '/Visual/ThreeJS/source/postprocessing/OutlinePass.js'; // 模型边框高亮
import { Pass } from '/Visual/ThreeJS/source/postprocessing/Pass.js'; //
import { RenderPass } from '/Visual/ThreeJS/source/postprocessing/RenderPass.js'; // 渲染通道,该通道在指定的场景和相机的基础上渲染出一个新场景
import { SAOPass } from '/Visual/ThreeJS/source/postprocessing/SAOPass.js'; //
import { SavePass } from '/Visual/ThreeJS/source/postprocessing/SavePass.js'; //
import { ShaderPass } from '/Visual/ThreeJS/source/postprocessing/ShaderPass.js'; // 接受自定义的着色器作为参数,以生成一个高级、自定义的后期处理通道, 产生各种模糊效果和高级滤镜
import { SMAAPass } from '/Visual/ThreeJS/source/postprocessing/SMAAPass.js'; //
import { SSAARenderPass } from '/Visual/ThreeJS/source/postprocessing/SSAARenderPass.js'; //
import { SSAOPass } from '/Visual/ThreeJS/source/postprocessing/SSAOPass.js'; //
import { SSRPass } from '/Visual/ThreeJS/source/postprocessing/SSRPass.js'; //
import { SSRrPass } from '/Visual/ThreeJS/source/postprocessing/SSRrPass.js'; //
import { TAARenderPass } from '/Visual/ThreeJS/source/postprocessing/TAARenderPass.js'; //
import { TexturePass } from '/Visual/ThreeJS/source/postprocessing/TexturePass.js'; // 保存当前通道的输出,作为后续使用
import { UnrealBloomPass } from '/Visual/ThreeJS/source/postprocessing/UnrealBloomPass.js'; //
import { ACESFilmicToneMappingShader } from '/Visual/ThreeJS/source/shaders/ACESFilmicToneMappingShader.js'; //
import { AfterimageShader } from '/Visual/ThreeJS/source/shaders/AfterimageShader.js'; //
import { BasicShader } from '/Visual/ThreeJS/source/shaders/BasicShader.js'; //
import { BleachBypassShader } from '/Visual/ThreeJS/source/shaders/BleachBypassShader.js'; // 创造一种镀银的效果
import { BlendShader } from '/Visual/ThreeJS/source/shaders/BlendShader.js';
import { BokehShader } from '/Visual/ThreeJS/source/shaders/BokehShader.js';
import { BokehShader as BokehShader2, BokehDepthShader } from '/Visual/ThreeJS/source/shaders/BokehShader2.js';
import { BrightnessContrastShader } from '/Visual/ThreeJS/source/shaders/BrightnessContrastShader.js'; // 改变亮度和对比度
import { ColorCorrectionShader } from '/Visual/ThreeJS/source/shaders/ColorCorrectionShader.js'; // 调整颜色的分布
import { ColorifyShader } from '/Visual/ThreeJS/source/shaders/ColorifyShader.js'; // 将某种颜色覆盖到整个屏幕
import { ConvolutionShader } from '/Visual/ThreeJS/source/shaders/ConvolutionShader.js';
import { CopyShader } from '/Visual/ThreeJS/source/shaders/CopyShader.js';
import { DepthLimitedBlurShader } from '/Visual/ThreeJS/source/shaders/DepthLimitedBlurShader.js';
import { DigitalGlitch } from '/Visual/ThreeJS/source/shaders/DigitalGlitch.js';
import { DOFMipMapShader } from '/Visual/ThreeJS/source/shaders/DOFMipMapShader.js';
import { DotScreenShader } from '/Visual/ThreeJS/source/shaders/DotScreenShader.js';
import { FilmShader } from '/Visual/ThreeJS/source/shaders/FilmShader.js';
import { FocusShader } from '/Visual/ThreeJS/source/shaders/FocusShader.js'; // 创建中间比较尖锐,周围比较模糊的效果。
import { FreiChenShader } from '/Visual/ThreeJS/source/shaders/FreiChenShader.js';
import { FXAAShader } from '/Visual/ThreeJS/source/shaders/FXAAShader.js'; // 添加抗锯齿的效果
import { GammaCorrectionShader } from '/Visual/ThreeJS/source/shaders/GammaCorrectionShader.js';
import { GodRaysDepthMaskShader, GodRaysGenerateShader, GodRaysCombineShader, GodRaysFakeSunShader } from '/Visual/ThreeJS/source/shaders/GodRaysShader.js';
import { HalftoneShader } from '/Visual/ThreeJS/source/shaders/HalftoneShader.js';
import { HorizontalBlurShader } from '/Visual/ThreeJS/source/shaders/HorizontalBlurShader.js'; // 可以向水平和垂直方向创建模糊效果
import { VerticalBlurShader } from '/Visual/ThreeJS/source/shaders/VerticalBlurShader.js'; // 可以向水平和垂直方向创建模糊效果
import { HorizontalTiltShiftShader } from '/Visual/ThreeJS/source/shaders/HorizontalTiltShiftShader.js'; // 可以在水平和垂直方向创建倾斜平移的效果
import { VerticalTiltShiftShader } from '/Visual/ThreeJS/source/shaders/VerticalTiltShiftShader.js'; // 可以在水平和垂直方向创建倾斜平移的效果
import { HueSaturationShader } from '/Visual/ThreeJS/source/shaders/HueSaturationShader.js'; // 改变颜色的色调和饱和度
import { KaleidoShader } from '/Visual/ThreeJS/source/shaders/KaleidoShader.js'; // 类似于万花筒的效果
import { LuminosityHighPassShader } from '/Visual/ThreeJS/source/shaders/LuminosityHighPassShader.js';
import { LuminosityShader } from '/Visual/ThreeJS/source/shaders/LuminosityShader.js'; // 提高亮度
import { MirrorShader } from '/Visual/ThreeJS/source/shaders/MirrorShader.js'; // 创建镜面效果
import { MMDToonShader } from '/Visual/ThreeJS/source/shaders/MMDToonShader.js';
import { NormalMapShader } from '/Visual/ThreeJS/source/shaders/NormalMapShader.js';
import { PixelShader } from '/Visual/ThreeJS/source/shaders/PixelShader.js';
import { RGBShiftShader } from '/Visual/ThreeJS/source/shaders/RGBShiftShader.js'; // 将红绿蓝三种颜色分开
import { SAOShader } from '/Visual/ThreeJS/source/shaders/SAOShader.js';
import { SepiaShader } from '/Visual/ThreeJS/source/shaders/SepiaShader.js'; // 创建类似于乌贼墨的效果
import { SMAAEdgesShader, SMAAWeightsShader, SMAABlendShader } from '/Visual/ThreeJS/source/shaders/SMAAShader.js';
import { SobelOperatorShader } from '/Visual/ThreeJS/source/shaders/SobelOperatorShader.js';
import { SSAOShader } from '/Visual/ThreeJS/source/shaders/SSAOShader.js';
import { SSRrShader } from '/Visual/ThreeJS/source/shaders/SSRrShader.js';
import { SSRShader } from '/Visual/ThreeJS/source/shaders/SSRShader.js';
import { SubsurfaceScatteringShader } from '/Visual/ThreeJS/source/shaders/SubsurfaceScatteringShader.js'; // 模拟类似老电影里面的两条彩色效果
import { TechnicolorShader } from '/Visual/ThreeJS/source/shaders/TechnicolorShader.js';
import { ToneMapShader } from '/Visual/ThreeJS/source/shaders/ToneMapShader.js';
import { ToonShader1, ToonShader2, ToonShaderHatching, ToonShaderDotted } from '/Visual/ThreeJS/source/shaders/ToonShader.js';
import { TriangleBlurShader } from '/Visual/ThreeJS/source/shaders/TriangleBlurShader.js'; // 基于三角形的方法创造一种模糊效果
import { UnpackDepthRGBAShader } from '/Visual/ThreeJS/source/shaders/UnpackDepthRGBAShader.js';
import { VignetteShader } from '/Visual/ThreeJS/source/shaders/VignetteShader.js'; // 添加晕映效果
import { VolumeRenderShader1 } from '/Visual/ThreeJS/source/shaders/VolumeShader.js';
import { WaterRefractionShader } from '/Visual/ThreeJS/source/shaders/WaterRefractionShader.js';
碰撞检测
- https://www.jb51.net/article/182528.htm
- http://webmaestro.fr/collisions-detection-three-js-raycasting/
Raycaster事件
光线投射Raycaster
https://threejs.org/docs/#api/zh/core/Raycaster
对于网格,面(faces)必须朝向射线原点,这样才能被检测到;通过背面的射线的交叉点将不被检测到。 为了光线投射一个对象的正反两面,你得设置 material 的 side 属性为 THREE.DoubleSide
mousemove事件 click事件
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
function onMouseMove( event ) { // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
window.addEventListener( 'mousemove', onMouseMove, false );
document.addEventListener( 'pointermove', onPointerMove );
document.addEventListener( 'pointerdown', onPointerDown );
document.addEventListener( 'keydown', onDocumentKeyDown );
document.addEventListener( 'keyup', onDocumentKeyUp );
let INTERSECTED = null;
function updateRender() {
// 通过摄像机和鼠标位置更新射线
raycaster.setFromCamera( mouse, Camera );
// 计算物体和射线的焦点 | 检测所有在射线与物体之间,包含或不包含后辈的相交局部。返回后果时,相交局部将按间隔进行排序,最近的位于第一个。
const intersects = raycaster.intersectObjects( Scene.children );
const isValid = INTERSECTED && INTERSECTED.material && INTERSECTED.material.emissive;
if ( intersects.length > 0 ) {
// intersects[ 0 ]对象的属性与方法
// scene.remove( intersect[0].object ); // 移除物体
// 当前焦点目标并非上一个目标
if ( intersects[ 0 ].object !== INTERSECTED ) {
if ( isValid ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
INTERSECTED = intersects[ 0 ].object;
if (INTERSECTED.material.emissive) {
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
INTERSECTED.material.emissive.setHex( 0xff0000 );
}
}
} else {
if ( isValid ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
INTERSECTED = null;
}
}
function animate() {
requestAnimationFrame( animate );
orbitControls.update();
updateRender();
RENDERER.render( SCENE, CAMERA );
}
animate();
性能优化方案
基础示例
// 计算这个mesh在gpu中所占内存
BufferGeometryUtils.estimateBytesUsed( mesh.geometry ) + " bytes"
// 使用DefaultUVEncoding降低内存数
GeometryCompressionUtils.compressUvs( mesh );
// 使用QuantizePosEncoding降低内存数
GeometryCompressionUtils.compressPositions( mesh );
// 使用NormEncodingMethods降低内存数
// [ "None", "DEFAULT", "OCT1Byte", "OCT2Byte", "ANGLES" ]
GeometryCompressionUtils.compressNormals( mesh, 'None' );
辅助工具库
three.interaction.js
给物体添加事件机制
GitHub:https://github.com/jasonChen1982/three.interaction.js 官网:https://jasonchen1982.github.io/three.interaction.js/docs/ 案例:https://jasonchen1982.github.io/three.interaction.js/examples/interaction/
stats
性能监控
ammo.js
- GitHub:https://github.com/kripken/ammo.js/