Skip to content

Commit 34e26c9

Browse files
committed
fix: destroy canvas properly
1 parent f27f840 commit 34e26c9

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

libs/angular-three/src/lib/canvas.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ export class NgtCanvas extends NgtRxStore<NgtCanvasInputs> implements OnInit, On
243243
if (this.glRef) this.glRef.destroy();
244244
if (this.glEnvInjector) this.glEnvInjector.destroy();
245245
injectNgtLoader.destroy();
246+
this.store.destroy(this.glCanvas.nativeElement);
246247
super.ngOnDestroy();
247248
}
248249

libs/angular-three/src/lib/stores/store.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,33 @@ export class NgtStore extends NgtRxStore<NgtState> {
384384
this.invalidate();
385385
}
386386

387+
destroy(canvas: HTMLCanvasElement) {
388+
this.set((state) => ({
389+
internal: { ...state.internal, active: false },
390+
}));
391+
392+
setTimeout(() => {
393+
const { gl, xr, events } = this.get();
394+
if (gl) {
395+
if (events.disconnect) {
396+
events.disconnect();
397+
}
398+
399+
gl.renderLists.dispose();
400+
gl.forceContextLoss();
401+
402+
if (gl.xr && gl.xr.enabled) {
403+
gl.xr.setAnimationLoop(null);
404+
xr.disconnect();
405+
}
406+
407+
dispose(this.get());
408+
409+
rootStateMap.delete(canvas);
410+
}
411+
}, 500);
412+
}
413+
387414
private resize() {
388415
const state = this.get();
389416
let oldSize = state.size;
@@ -428,3 +455,12 @@ function computeInitialSize(canvas: HTMLCanvasElement | THREE.OffscreenCanvas, d
428455

429456
return { width: 0, height: 0, top: 0, left: 0 };
430457
}
458+
459+
// Disposes an object and all its properties
460+
function dispose<TObj extends { dispose?: () => void; type?: string; [key: string]: any }>(obj: TObj) {
461+
if (obj.dispose && !is.scene(obj)) obj.dispose();
462+
for (const p in obj) {
463+
(p as any).dispose?.();
464+
delete obj[p];
465+
}
466+
}

0 commit comments

Comments
 (0)