近期在做three.js相关优化,想实现本地缓存模型功能,缩短模型加载时间。 在网上搜了相关资料,没有找到我想用的,终于研究明白了,下面讲下实现过程,如果有优化建议可以提出来,共同进步!
1. 创建indexedDB数据库
在浏览器中创建表结构,表可以在 应用 =》存储 =》indexedDB 中查看
var db;
var request = window.indexedDB.open("webDB", 1);
request.onerror = function (event) {
console.log("数据库打开报错");
};
request.onsuccess = function (event) {
db = request.result;
console.log("数据库打开成功");
};
request.onupgradeneeded = function (event) {
db = event.target.result;
var objectStore;
if (!db.objectStoreNames.contains("book")) {
objectStore = db.createObjectStore("book", {
keyPath: "id",
});
objectStore.createIndex("id", "id", {
unique: true,
});
objectStore.createIndex("name", "name");
objectStore.createIndex("model", "model");
}
console.log("数据库升级成功");
};
function add(book) {
var request1 = db
.transaction(["book"], "readwrite")
.objectStore("book")
.add({
id: book.id,
name: book.name,
model: book.model,
});
request1.onsuccess = function (event) {
console.log("数据写入成功");
};
request1.onerror = function (event) {
console.log("数据写入失败");
};
request1.onabort = function (event) {
console.log("事务回滚");
};
}
2. 请求模型文件,并存到indexedDB中
这里我用的ajax
var ajax = new XMLHttpRequest();
ajax.open("get", "/static/three/xi.gltf");
ajax.send();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
let blob = new Blob([ajax.responseText]);
add({ id: 80, name: "xi", model: blob });
}
};
3.使用three.js加载模型***
从数据库中读取模型文件
var transaction = db.transaction("book", "readwrite");
var store = transaction.objectStore("book");
var dataRequest = store.index("id").get(80);
dataRequest.onsuccess = function (e) {
console.log(e.target.result.model);
var url2 = URL.createObjectURL(e.target.result.model);
console.log(url2);
this.GLTFLoader = new GLTFLoader();
this.GLTFLoader.setDRACOLoader(this.DRACOLoader);
this.GLTFLoader.load(url2, (gltf) => {
console.log(gltf);
resolve(gltf.scene);
});
};
4.收获成功的喜悦
|