three.js 之 销毁

2023-02-27 32 three.js

介绍

three.js 之 销毁模型和销毁场景

# three.js的场景销毁

three.js的场景销毁的销毁, 销毁整个画布的操作, 通常用于路由切换后的清除之前的画布, 动画和监听

// 创建渲染器
const renderer = new THREE.WebGLRenderer()
// 设置场景
const scene = new THREE.Scene()
// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement)
// 动画渲染方法
const animationId = requestAnimationFrame()

// 清除场景, Object3D中的clear()方法, 清除所有子对象, 清除通过.add添加的内容
scene.clear()
// 清除轨道控制器
controls.dispose()
// 清除渲染器
renderer.dispose()
// 释放内存
// this.renderer.forceContextLoss()
// 清除动画
cancelAnimationFrame(this.animationId)
// 销毁监听
window.removeEventListener('resize', this.onWindowResize)

复制代码

# three.js的物体销毁

通常我们会把物体装进一个Group (opens new window)组中, Group的基类是Object3D, 那么就存在两种销毁方法

最后还会通过geometry (opens new window) 几何对象.dispose( ) (opens new window) 销毁方法, 把创建的几何对象也销毁掉, 如果觉得网格模型整体不会再出现, 还可以通过赋值为null触发js内存回收机制, 释放内存

// 创建一个组
const glassPanel = new THREE.Group()
// 创建一个网格模型
const demoMesh = new THREE.Mesh(geometry, material)

// 销毁组中的全部子类
// glassPanel.clear()
// 销毁组中的网格模型
glassPanel.remove(this.demoMesh)
// 销毁该网格模型的几何对象
demoMesh.geometry.dispose()
// (可选)利用js内存回收机制, 清除创建的网格模型对象
demoMesh = null as null
复制代码
Last Updated: 2023/2/28 12:36:59
来发评论吧~
Powered By Valine
v1.4.14
未加载音频 - (ಗ ‸ ಗ )
00:00 / 00:00