您的位置:首页 > 房产 > 建筑 > Babylonjs学习笔记(十四)——通IndexDB缓存模型

Babylonjs学习笔记(十四)——通IndexDB缓存模型

2025/5/6 3:43:38 来源:https://blog.csdn.net/weixin_41718879/article/details/140845233  浏览:    关键词:Babylonjs学习笔记(十四)——通IndexDB缓存模型

虽然babylonjs有使用IndexDB缓存的方案,但只针对.babylon的场景文件,通常情况下,我们的模型为.glb,.gltf格式,所以得自己撸一套方案

一、创建IndexDB工具函数
import { Nullable } from '@babylonjs/core';export class IndexDBWrapper {private db: Nullable<IDBDatabase> = null;constructor(private dbName: string, private storeName: string) {}async open(): Promise<void> {return new Promise((resolve, rejects) => {const request = indexedDB.open(this.dbName, 1);request.onerror = () => rejects(request.error);request.onsuccess = () => {this.db = request.result;resolve();};request.onupgradeneeded = (event) => {const db = (event.target as IDBOpenDBRequest).result;db.createObjectStore(this.storeName);};});}async get(key: string): Promise<any> {return new Promise((resolve, reject) => {if (!this.db) reject(new Error('DB 未打开'));const transaction = this.db?.transaction(this.storeName, 'readonly');const store = transaction?.objectStore(this.storeName);const request = store?.get(key);request!.onerror = () => reject(request?.error);request!.onsuccess = () => resolve(request?.result);});}async set(key: string, value: any): Promise<void> {return new Promise((resolve, reject) => {if (!this.db) reject(new Error('DB 未打开'));const transaction = this.db?.transaction(this.storeName, 'readwrite');const store = transaction?.objectStore(this.storeName);const request = store?.put(value, key);request!.onerror = () => reject(request?.error);request!.onsuccess = () => resolve();});}
}
二、使用

const dBWrapper = new IndexDBWrapper()private async importModel():Promise<void>{await dBWrapper.open();// 从缓存获取const cachedModel = await dBWrapper.get('earth-origin');if (cachedModel) {console.log('load from cache');await SceneLoader.ImportMeshAsync('', '', `data:${cachedModel}`, scene, (meshes) => {});} // 从文件加载else {const { meshes} = await SceneLoader.ImportMeshAsync('', 'path to your model', 'xxx.glb');const serializedScene = SceneSerializer.Serialize(this.scene);await this.dBWrapper.set('earth-origin', JSON.stringify(serializedScene));}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com