Laya使用zip压缩包

JSZip

游戏中有大量配置文件时,经常为了减少配置文件的加载时间需要将配置文件打包成zip文件,然后只需加载一次zip文件,使用JSZip库将配置文件从zip文件中解压读取出来即可。
JSZip官网:JSZip
官方提供的JSZip中只有JS文件,我们使用TS开发时为了方便使用需要d.ts文件。这里我提供一个我自己使用dtsmake
转换后的3.1版本的JSzip库和jszip.d.ts文件的下载地址。

引用JSZip

  • 将js文件复制到项目的bin/libs文件夹下。


    JSZip_0.png
  • 将d.ts文件复制到项目的libs文件夹下。


    JSZip_1.png
  • 在index.js文件中引入js库

loadLib('libs/jszip.js')

读取zip包中文本内容

        //先以二进制方式加载zip包
        Laya.loader.load([{ type: Laya.Loader.BUFFER, url: 'res/testFileZip.zip' }], Laya.Handler.create(this, () => {
            const jsZip = new JSZip();
            //获取ZIP包内容传入JSZip中解析
            jsZip.loadAsync(Laya.loader.getRes('res/testFileZip.zip')).then((data: any) => {
                //以text的方式读取testFile.txt内容
                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包内容传入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);
                })
            })
        }))

你可能感兴趣的:(Laya使用zip压缩包)