// 添加数据到indexdb
addData(data) {
let modelStorage = db
.transaction('threeDModelFile', 'readwrite') // 事务对象 指定表格名称和操作模式("只读"或"读写")
.objectStore('threeDModelFile') // 仓库对象
.add(data);
modelStorage.onsuccess = function(event) {
console.log('数据写入成功');
};
modelStorage.onerror = function(event) {
console.log('数据写入失败');
throw new Error(event.target.error);
};
},
// 根据id获取数据
getDataByKey(key) {
let transaction = db.transaction('threeDModelFile'); // 事务
let objectStore = transaction.objectStore('threeDModelFile'); // 仓库对象
let modelStorage = objectStore.get(key);
return modelStorage;
},
//加载3D模型
initGLTF() {
// 创建indexDB内存数据库,存储基础路段数据
let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
if (!indexedDB) {
this.loadGltf(that.threeDModelPath);
// 使用vuex进行缓存,否则使用indexdb缓存,
} else {
let that = this;
let modelId = this.$route.query.id;
this.showLoading = true;
indexDB = indexedDB.open('threeDModelFile');
// 数据库首次创建版本,或者window.indexedDB.open传递的新版本(版本数值要比现在的高)
indexDB.onupgradeneeded = function(event) {
db = event.target.result;
if (!db.objectStoreNames.contains('threeDModelFile')) {
objectStore = db.createObjectStore('threeDModelFile', { keyPath: 'id' }); // 定义主键,相当于id
objectStore.createIndex('modelFile', 'modelFile', { unique: false });
}
};
// 数据库成功打开
indexDB.onsuccess = function(event) {
//获取db容器
db = indexDB.result;
//判断是否有值--objectStore数据存储仓库(表)
objectStore = db.transaction('threeDModelFile', 'readonly').objectStore('threeDModelFile');
//此处根据里面是否有sectionCode=0的数据来判断是否已存储路段数据
let modelStorage = that.getDataByKey(Number(modelId));
modelStorage.onsuccess = function(event) {
if (modelStorage.result) {
// 从缓存中取出
var url = URL.createObjectURL(modelStorage.result.modelFile);
that.loadGltf(url);
} else {
that.loadGltf(that.threeDModelPath, true);
}
};
};
// 错误处理
indexDB.onerror = function(event) {
console.log('error', event);
};
}
},
loadGltf(url, flag = false) {
let modelId = this.$route.query.id;
// 通过gltf加载器加载url
let that = this;
var loader = new GLTFLoader();
try {
loader.load(
url,
gltf => {
that.showLoading = false;
that.hasLoaded = true;
gltf.scene.scale.set(1, 1, 1);
gltf.scene.position.set(0, 0, 0);
gltf.scene.traverse(item => {
if (item instanceof THREE.Mesh) {
item.material = item.material.clone();
}
});
scene.add(gltf.scene);
that.animate();
},
function(xhr) {
//把加载进度数据取整然后传递给Vue组件:进度条
if (that.$refs.threeDLoading) that.$refs.threeDLoading.percentage = Math.floor((xhr.loaded / xhr.total) * 100);
if (flag && xhr.loaded === xhr.total) {
//数据入表
that.addData({
id: Number(modelId),
modelFile: new Blob([xhr.currentTarget.response]),
});
}
},
);
} catch (err) {
that.showLoading = false;
that.$message.error('3D文件未上传或出错,无法加载!');
}
},
3d模型文件存入浏览器indexDB,加快模型加载速度
于 2023-02-03 14:31:14 首次发布