1.定义清空方法:
export default class ResourceTracker {
constructor() {
this.resources = new Set();
}
track(resource) {
if (!resource) {
return resource;
}
// handle children and when material is an array of materials or
// uniform is array of textures
if (Array.isArray(resource)) {
resource.forEach((resource) => this.track(resource));
return resource;
}
if (resource.dispose || resource instanceof THREE.Object3D) {
this.resources.add(resource);
}
if (resource instanceof THREE.Object3D) {
this.track(resource.geometry);
this.track(resource.material);
this.track(resource.children);
} else if (resource instanceof THREE.Material) {
// We have to check if there are any textures on the material
for (const value of Object.values(resource)) {
if (value instanceof THREE.Texture) {
this.track(value);
}
}
// We also have to check if any uniforms reference textures or arrays of textures
if (resource.uniforms) {
for (const value of Object.values(resource.uniforms)) {
if (value) {
const uniformValue = value.value;
if (
uniformValue instanceof THREE.Texture ||
Array.isArray(uniformValue)
) {
this.track(uniformValue);
}
}
}
}
}
return resource;
}
untrack(resource) {
this.resources.delete(resource);
}
dispose() {
for (const resource of this.resources) {
if (resource instanceof THREE.Object3D) {
if (resource.parent) {
resource.parent.remove(resource);
}
}
if (resource.dispose) {
resource.dispose();
}
}
this.resources.clear();
}
}
2.在相应页面引入
import ResourceTracker from "../util/common.js"
// 在外层定义resMgr和track
let resMgr = new ResourceTracker();
const track = resMgr.track.bind(resMgr);
3.在每个需要add的方法上,使用track
包起来
像这样
// 计算模型中心
const explodeBox = track(new THREE.Box3());
const boxHelper = track(new THREE.BoxHelper(obj));
track(new THREE.Vector3()).copy(center).add(distance).sub(offset);
4.定义清空方法
clearObj () {
scene.clear();
// this.loadMTL()
resMgr && resMgr.dispose()
renderer.dispose();
renderer.forceContextLoss();
renderer.content = null;
if (this.isAnimate !== null) {
cancelAnimationFrame(this.isAnimate);
}
let gl = renderer.domElement.getContext("webgl");
gl && gl.getExtension("WEBGL_lose_context").loseContext();
},
5.调用
beforeDestroy () {
this.clearObj();
}
总结:若是需要动态切换模型的话,你在调用该方法后,还需要重新调用一次加载模型的方法,并且在更换新模型时,还需要清除上一个模型的canvas