Three.js清除场景/模型释放内存

在开发3D场景时,若遇到需要动态添加删改模型、场景,页面切换重渲染时,为避免内存叠加占用,需要手动清除场景所占用的内存,避免溢出与资源浪费。

  • 使用 dispose() 清除所有网格模型几何体的顶点缓冲区占用内存
  • 使用 object.clear() 销毁模型对象,清除页面内存
  • 暂停 requestAnimationFrame() 方法,避免无意义运行
  • 清空 canvas画布,置空dom与相关元素
清除场景
 clearScene() {
    cancelAnimationFrame(this.animationId);
    this.scene.traverse((child) => {
      if (child.material) {
        child.material.dispose();
      }
      if (child.geometry) {
        child.geometry.dispose();
      }
      child = null;
    });
    this.sceneDomElement.innerHTML = '';
    this.renderer.forceContextLoss();
    this.renderer.dispose();
    this.scene.clear();
    this.flows = [];
    this.scene = null;
    this.camera = null;
    this.controls = null;
    this.renderer.domElement = null;
    this.renderer = null;
    this.sceneDomElement = null;
    console.log('clearScene');
  }
清除Group
 clearGroup(group) {
    const clearCache = (item) => {
      item.geometry.dispose();
      item.material.dispose();
    };
    const removeObj = (obj) => {
      let arr = obj.children.filter((x) =>!! x);
      arr.forEach((item) => {
        if (item.children.length) {
          removeObj(item);
        } else {
          clearCache(item);
          item.clear();
        }
      });
      obj.clear();
      arr = null;
    };
    removeObj(group);
  }
删除场景中的指定的某个模型/Group
scene.remove(group); // 删除组

group.remove(mesh);// 删除模型
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值