search
HomeWeb Front-endH5 TutorialCode example of application of Zip compression and decompression technology in HTML5 (picture)

JSZip is a javaScript tool that can create, read, and modify .zip files. In web applications, it is inevitable to obtain resources from the web server. If all resources can be merged into a .zip file, then only one request is required, which not only reduces the pressure on the server, but also speeds up the web process. The application's rendering speed.

Today let’s discuss how JSZip is combined with HT applications. Let’s take a look at the renderings of this Demo:

The first step is to package the application and related resources into a .zip file,

#This is the list of files I want to compress, store the corresponding resource files in the corresponding folder, and then indicate the resource loading in the loadorder file In order, the content of the loadorder file is as follows:

'js/ht.js',

'js/ht-obj.js',

'js/ht-modeling.js',

'obj/equipment.mtl',

'obj/equipment.obj',

'image/equipment.jpg'

In the resource loading order, the path of the response resource relative to the .zip file should be indicated, so that it can be quickly found when reading the .zip file. Corresponding resource files.

The second step is to introduce JSZip and the JSZipUtils library into the html file. The next step is to request the .zip file and parse the .zip file.

JSZipUtils.getBinaryContent('res/ImportObj.zip', function(err, data) {
    if(err) {
        throw err; // or handle err
    }
    var zip = new JSZip(data);

    var loadorderStr = zip.file('loadorder').asText(),
            order;
    eval('order = [' + loadorderStr + ']');
    var len = order.length,
            image = {},
            mtlStr = '',
            objStr = '';
    for(var i = 0; i < len; i++) {
        var fileName = order[i];
        if(fileName.indexOf(&#39;js/&#39;) >= 0) {
            var js = document.createElement(&#39;script&#39;);
            js.innerHTML = zip.file(fileName).asText();
            document.getElementsByTagName(&#39;head&#39;)[0].appendChild(js);
        } else if(fileName.indexOf(&#39;image/&#39;) >= 0) {
            var buffer = zip.file(fileName).asArrayBuffer(),
                    str = _arrayBufferToBase64(buffer),
                    pIndex = fileName.indexOf(&#39;.&#39;),
                    type = fileName.substr(pIndex + 1),
                    re = &#39;data:image/&#39; + type + &#39;;base64,&#39;;

            image[fileName] = re + str;
        } else if(fileName.indexOf(&#39;obj/&#39;) >= 0) {
            var str = zip.file(fileName).asText();
            if(fileName.indexOf(&#39;.mtl&#39;) > 0) {
                mtlStr = str;
            } else if(fileName.indexOf(&#39;.obj&#39;) > 0) {
                objStr = str;
            }
        }
    }

    init(objStr, mtlStr, image);
});

First obtain the .zip file through JSZipUtils, and load the obtained file content into the zip through the new JSZip(data) method Variable , read the loadorder file content through zip.file(fileName), use the eval command to dynamically execute the script, convert the text content into the js variable order, and finally, by traversing the order variable, dynamically introduce the js resource into the page.

There are image files in the .zip file. JSZip can only obtain the ArrayBuffer data of the image file. At this time, the ArrayBuffer needs to be converted to Base64 to be recognized by the browser, so A conversion function is defined here: _arrayBufferToBase64

function _arrayBufferToBase64( buffer ) {
    var binary = &#39;&#39;;
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

This case involves 3D model data and HT 3D topology application The obj directory in the .zip file stores 3D model data. During file reading, the 3D model data is read out in the form of text pairs and stored in variables, and then the data is passed to the init function, through ht The .Default.parseObj() method loads 3D model data into HT.

function init(objStr, mtlStr, image) {
    dataModel = new ht.DataModel();
    g3d = new ht.graph3d.Graph3dView(dataModel);

    view = g3d.getView();
    view.className = &#39;main&#39;;
    document.body.appendChild(view);
    window.addEventListener(&#39;resize&#39;, function (e) {
        g3d.invalidate();
    }, false);

    g3d.setEye([0, 500, 1000]);
    g3d.setCenter([0, 200, 0]);
    g3d.setGridVisible(true);
    g3d.setGridColor(&#39;#74AADA&#39;);

    var param = {
        shape3d: &#39;E1&#39;,
        center: true,
        cube: true
    };

    var modelMap = ht.Default.parseObj(objStr, mtlStr, param);
    for(var model in modelMap) {
        var map = modelMap[model],
                i = map.image,
                index = i.lastIndexOf(&#39;/&#39;),
                fileName = i.substr(index + 1),
                rawS3 = map.rawS3;
        for(var imgName in image) {
            if(imgName.indexOf(fileName) >= 0) {
                ht.Default.setImage(i, 256, 256, image[imgName]);
            }
        }
    }

    var node = new ht.Node();
    node.s({
        &#39;shape3d&#39;: &#39;E1&#39;,
        &#39;wf.visible&#39;: &#39;selected&#39;,
        &#39;wf.width&#39;: 3,
        &#39;wf.color&#39;: &#39;#F7F691&#39;
    });
    node.s3(param.rawS3);
    node.p3(0, param.rawS3[1]/2, 0);
    dataModel.add(node);
}

The above is the code to generate 3D topology, 3D model introduction and reference 3D model creation topology node. The setImage code needs special attention. Why do I have to go through so much trouble to determine the file name of the image? That’s because there is a attribute for setting the texture in the mtl 3D model description file. This The attribute can specify the absolute path of the file or the relative path of the file. Because JSZip cannot write the file contents in the .zip back to the local directory, the attribute name corresponding to the texture attribute can only be used as HT# The image name in ## is set to HT so that when the HT model is loaded, the image resources required by the model can be obtained. For the application of HT 3D topology, please refer to "3D Topology Automatic Layout Node.jsPart".

JSZip If the speed is slow when compressing or decompressing data, you can consider using Web Worker.

The above is the detailed content of Code example of application of Zip compression and decompression technology in HTML5 (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use