JSZip
游戲中有大量配置文件時混萝,經(jīng)常為了減少配置文件的加載時間需要將配置文件打包成zip文件裁奇,然后只需加載一次zip文件,使用JSZip庫將配置文件從zip文件中解壓讀取出來即可憔披。
JSZip官網(wǎng):JSZip
官方提供的JSZip中只有JS文件撑刺,我們使用TS開發(fā)時為了方便使用需要d.ts文件。這里我提供一個我自己使用dtsmake
轉(zhuǎn)換后的3.1版本的JSzip庫和jszip.d.ts文件的下載地址所宰。
引用JSZip
-
將js文件復(fù)制到項目的bin/libs文件夾下绒尊。
-
將d.ts文件復(fù)制到項目的libs文件夾下。
在index.js文件中引入js庫
loadLib('libs/jszip.js')
讀取zip包中文本內(nèi)容
//先以二進制方式加載zip包
Laya.loader.load([{ type: Laya.Loader.BUFFER, url: 'res/testFileZip.zip' }], Laya.Handler.create(this, () => {
const jsZip = new JSZip();
//獲取ZIP包內(nèi)容傳入JSZip中解析
jsZip.loadAsync(Laya.loader.getRes('res/testFileZip.zip')).then((data: any) => {
//以text的方式讀取testFile.txt內(nèi)容
data.file('testFile.txt').async('text').then((content:string) =>{
console.log(content);
})
})
}))
讀取zip包中圖片的base64信息
//先以二進制方式加載zip包
Laya.loader.load([{ type: Laya.Loader.BUFFER, url: 'res/testFileZip.zip' }], Laya.Handler.create(this, () => {
const jsZip = new JSZip();
//獲取ZIP包內(nèi)容傳入JSZip中解析
jsZip.loadAsync(Laya.loader.getRes('res/testFileZip.zip')).then((data: any) => {
//以base64的方式讀取skillIcon.png并顯示在屏幕上
data.file('skillIcon.png').async('base64').then((content:string) =>{
const testPng = new Laya.Image();
testPng.skin = 'data:image/png;base64,' + content
//testPng.loadImage();
Laya.stage.addChild(testPng);
console.log(content);
})
})
}))