search
HomeWeb Front-endH5 TutorialHTML5 game framework cnGameJS development record-detailed explanation of resource loading module code

1. Functions  

This module is the entrance to the game. We load resources through this module and call the entry function of the game object after the resources are loaded. In addition, this module also includes switching between game scenes, as well as the calculation and display of loading percentage.

When starting the game, first pass in the list of resources that need to be loaded, then pass in the game object, and finally pass in the function that is called after each resource is loaded. This function can get the loading percentage. As follows:

cnGame.loader.start(["src1","src2","src3"],gameObj,function(loadedPercent){});

In this case, the three image resources passed in earlier will be loaded first, and each time a picture is loaded, the following callback function will be called, The The function can obtain the loading percentage, implement the loading interface, tell the user the current loading progress and other functions. When loading is complete, call the initialize method of the game object gameObj to start the game.

2. Specific implementation:

First, let’s look at the code of the loader:

/**
     *图像加载器
    **/    
    var loader={
        sum:0,            //图片总数
        loadedCount:0,    //图片已加载数
        loadingImgs:{}, //未加载图片集合
        loadedImgs:{},    //已加载图片集合
        /**
         *图像加载,之后启动游戏
        **/    
        start:function(src,gameObj,onLoad){//可传入src数组或单个src "xxx.jpg" or ["xxx.jpg","ggg,gif","www.png"]
        
            if(cg.core.isArray(src)){ 
                this.sum=src.length;
                for(var i=0,len=src.length;i<len;i++){
                    this.gameObj=gameObj;
                    this.onLoad=onLoad;
                    this.loadingImgs[src[i]]=new Image();
                    this.loadingImgs[src[i]].onload=imgLoad(this);
                    this.loadingImgs[src[i]].src=src[i];
                    this.loadingImgs[src[i]].srcPath=src[i];//没有经过自动变换的src
                }
                    
            }
            
        }
        
    }

First, the resource loader saves the following Fields: list of loaded resources, list of unloaded resources, total number of resources, total number of loaded resources. When the start method is called, the loader starts traversing the image srcarray and generates an image object for loading. In addition, we need to save srcPath for each image object, which is the original src parameter (because by default the browser will convert the src parameter into a complete image path) . The next step is to add an onLoad handler for each image. We need to calculate the loading percentage in this handler and save the loaded image object into the loadedImgs object to facilitate subsequent use by users. The processing procedure for image loading is as follows:

/**
     *图像加载完毕的处理程序
    **/    
    var imgLoad=function(self){
        return function(){
            self.loadedCount+=1;
            self.loadedImgs[this.srcPath]=this;
            this.onLoad=null;                    //保证图片的onLoad执行一次后销毁
            self.loadedPercent=Math.floor(self.loadedCount/self.sum*100);
            self.onLoad&&self.onLoad(self.loadedPercent);
            if(self.loadedPercent===100){
                self.loadedCount=0;
                self.loadedPercent=0;
                loadingImgs={};
                if(self.gameObj&&self.gameObj.initialize){
                    self.gameObj.initialize();
                    if(cg.loop&&!cg.loop.stop){//结束上一个循环
                        cg.loop.end();
                    }
                    cg.loop=new cg.GameLoop(self.gameObj);//开始新游戏循环
                    cg.loop.start();
                }
                
            }
            
        
        }
    }

After each image is loaded, the loading quantity is increased by 1, the image object is saved, and the percentage of loading completion is calculated. Finally, you need to delete the handler of the image (because the image has been loaded, the handler is useless and can be released to save memory resources). When the loading percentage is 100%, all values ​​are reset and loadingImgs is released for the next loading of resources. In addition, the game loop (the game loop is responsible for all game objects in each frame) The update and draw)

/**
 *
 *资源加载器
 *
**/
cnGame.register("cnGame",function(cg){

    /**
     *图像加载完毕的处理程序
    **/    
    var imgLoad=function(self){
        return function(){
            self.loadedCount+=1;
            self.loadedImgs[this.srcPath]=this;
            this.onLoad=null;                    //保证图片的onLoad执行一次后销毁
            self.loadedPercent=Math.floor(self.loadedCount/self.sum*100);
            self.onLoad&&self.onLoad(self.loadedPercent);
            if(self.loadedPercent===100){
                self.loadedCount=0;
                self.loadedPercent=0;
                loadingImgs={};
                if(self.gameObj&&self.gameObj.initialize){
                    self.gameObj.initialize();
                    if(cg.loop&&!cg.loop.stop){//结束上一个循环
                        cg.loop.end();
                    }
                    cg.loop=new cg.GameLoop(self.gameObj);//开始新游戏循环
                    cg.loop.start();
                }
                
            }
            
        
        }
    }
    /**
     *图像加载器
    **/    
    var loader={
        sum:0,            //图片总数
        loadedCount:0,    //图片已加载数
        loadingImgs:{}, //未加载图片集合
        loadedImgs:{},    //已加载图片集合
        /**
         *图像加载,之后启动游戏
        **/    
        start:function(src,gameObj,onLoad){//可传入src数组或单个src "xxx.jpg" or ["xxx.jpg","ggg,gif","www.png"]
        
            if(cg.core.isArray(src)){ 
                this.sum=src.length;
                for(var i=0,len=src.length;i<len;i++){
                    this.gameObj=gameObj;
                    this.onLoad=onLoad;
                    this.loadingImgs[src[i]]=new Image();
                    this.loadingImgs[src[i]].onload=imgLoad(this);
                    this.loadingImgs[src[i]].src=src[i];
                    this.loadingImgs[src[i]].srcPath=src[i];//没有经过自动变换的src
                }
                    
            }
            
        }
        
    }
    
    
    this.loader=loader;
});

The above is the detailed content of HTML5 game framework cnGameJS development record-detailed explanation of resource loading module code. 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
HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor