search
HomeWeb Front-endH5 TutorialHTML5 game framework cnGameJS development record - code example of core function module

Return to directory

##1.cnGameJs framework code organization

Core

Function The main function of the module is to facilitate subsequent framework development and user game development. The entire framework is in a closure to avoid contamination of the global scope. After that, each different module is in its own closure, making the separation of different modules clearer. Therefore, the module division of our framework will be like this:

(function(win,undefined){//最大的闭包

var fun1=function(){//各模块公用的方法
}

//这里放各个小模块,它们有各自的闭包

}(window,undefined)

So how do we divide other small modules? In order to facilitate each small module to have its own

namespace and in its own closure, we have added a register method, which can expand its own module under different namespaces , the first thing we need to pass in is the name of the namespace, this method generates the namespace object for us, and then we execute our own method to perform the corresponding expansion operation for the namespace object:

/**
         *生成命名空间,并执行相应操作
        **/
        register:function(nameSpace,func){
            var nsArr=nameSpace.split(".");
            var parent=win;
            for(var i=0,len=nsArr.length;i<len;i++){
                (typeof parent[nsArr[i]]==&#39;undefined&#39;)&&(parent[nsArr[i]]={});
                parent=parent[nsArr[i]];
            }
            if(func){
                func.call(parent,this);    
            }
            return parent;
        }

As above, first You can split the incoming namespace

string, then generate an object, and then execute the function passed in by the user for expansion operations, as follows:

cnGame.register("cnGame.core",function(){this.func=function(){}});

In this way, you can generate the core module , and add the func method to this module, then the code organization of our framework will look like this:

(function(win,undefined){

var cnGame={
    register:function(nameSpace,handler){

    }
}

/*core模块*/
cnGame.register("core",function(){
  //添加该模块内容
})

/*input模块*/
cnGame.register("input",function(){
  //添加该模块内容
})

win["cnGame"]=cnGame;


})(window,undefined);

 


2. Initialization of the framework

 Framework initialization When, the objects that need to be saved are:

canvas object, context object, canvas position, size, etc. We can first look at the initialization function:

/**
         *初始化
        **/
        init:function(id,options){
            options=options||{};
            this.canvas = this.core.$(id||"canvas");    
            this.context = this.canvas.getContext(&#39;2d&#39;);
            this.width = options.width||800;
            this.height = options.height||600;
            this.title = this.core.$$(&#39;title&#39;)[0];
            canvasPos=getCanvasPos(this.canvas);
            this.x=canvasPos[0]||0;
            this.y=canvasPos[1]||0;
            this.canvas.width=this.width;
            this.canvas.height=this.height;
            this.canvas.style.left=this.x +"px";
            this.canvas.style.top=this.y +"px";
            
        },

Very simple, just save Some initialization values ​​for subsequent use. In addition, you can notice that we called the getCanvasPos method to get the position parameter of the canvas. This parameter loops to get the off

setParent of the object, and superimposes offsetLeft and offsetTop to get the position of the canvas on the page. The source code of this function is as follows:

/**
    *获取canvas在页面的位置
    **/      
    var getCanvasPos=function(canvas){
        var left = 0;
        var top = 0;
        while (canvas.offsetParent) {
            left += canvas.offsetLeft;
            top += canvas.offsetTop;
            canvas = canvas.offsetParent;

        }
        return [left, top];

    }

3. Tool function module

After that, we can use the register method above to add the first module: core module. This module is also very simple. Its main function is to add tool functions to facilitate subsequent framework development and user game development. This contains some commonly used tool functions, such as getting elements by id, prototype

inheritance, object copy, eventbinding, etc.. Note that if there are compatibility issues with different browsers, we can set the function according to the browser from the beginning instead of judging the browser type every time and then perform corresponding operations, which will be more efficient. Take event binding as an example:

/**
        事件绑定
        **/
        this.bindHandler=(function(){
                            
                        if(window.addEventListener){
                            return function(elem,type,handler){
                                elem.addEventListener(type,handler,false);
                                
                            }
                        }
                        else if(window.attachEvent){
                            return function(elem,type,handler){
                                elem.attachEvent("on"+type,handler);
                            }
                        }
        })();

Return different functions according to browser characteristics in advance, so that subsequent use does not need to judge browser characteristics and improves efficiency.

Attached are the source codes of all tool functions. Since they are very simple, the module will not be described in detail.

/**
 *
 *基本工具函数模块
 *
**/
cnGame.register("cnGame.core",function(cg){
        /**
        按id获取元素
        **/
        this.$=function(id){
            return document.getElementById(id);        
        };
        /**
        按标签名获取元素
        **/
        this.$$=function(tagName,parent){
            parent=parent||document;
            return parent.getElementsByTagName(tagName);    
        };
        /**
        按类名获取元素
        **/
        this.$Class=function(className,parent){
            var arr=[],result=[];
            parent=parent||document;
            arr=this.$$("*");
            for(var i=0,len=arr.length;i0){
                    result.push(arr[i]);
                }
            }
            return result;    
        };
        /**
        事件绑定
        **/
        this.bindHandler=(function(){
                            
                        if(window.addEventListener){
                            return function(elem,type,handler){
                                elem.addEventListener(type,handler,false);
                                
                            }
                        }
                        else if(window.attachEvent){
                            return function(elem,type,handler){
                                elem.attachEvent("on"+type,handler);
                            }
                        }
        })();
        /**
        事件解除
        **/
        this.removeHandler=(function(){
                        if(window.removeEventListerner){
                            return function(elem,type,handler){
                                elem.removeEventListerner(type,handler,false);
                                
                            }
                        }
                        else if(window.detachEvent){
                            return function(elem,type,handler){
                                elem.detachEvent("on"+type,handler);
                            }
                        }
        })();
        /**
        获取事件对象
        **/
        this.getEventObj=function(eve){
            return eve||win.event;
        };
        /**
        获取事件目标对象
        **/
        this.getEventTarget=function(eve){
            var eve=this.getEventObj(eve);
            return eve.target||eve.srcElement;
        };
        /**
        禁止默认行为
        **/
        this.preventDefault=function(eve){
            if(eve.preventDefault){
                eve.preventDefault();
            }
            else{
                eve.returnValue=false;
            }
            
        };
        /**
        获取对象计算的样式
        **/
        this.getComputerStyle=(function(){
            var body=document.body;
            if(body.currentStyle){
                return function(elem){
                    return elem.currentStyle;
                }
            }
            else if(document.defaultView.getComputedStyle){
                return function(elem){
                    return document.defaultView.getComputedStyle(elem, null);    
                }
            }
            
        })();
        /**
        是否为undefined
        **/
        this.isUndefined=function(elem){
            return typeof elem==='undefined';
        },
        /**
        是否为数组
        **/
        this.isArray=function(elem){
            return Object.prototype.toString.call(elem)==="[object Array]";
        };
        /**
        是否为Object类型
        **/
        this.isObject=function(elem){
            return elem===Object(elem);
        };
        /**
        是否为字符串类型
        **/
        this.isString=function(elem){
            return Object.prototype.toString.call(elem)==="[object String]";
        };
        /**
        是否为数值类型
        **/
        this.isNum=function(elem){
            return Object.prototype.toString.call(elem)==="[object Number]";
        };
        /**
         *复制对象属性
        **/
        this.extend=function(destination,source,isCover){
            var isUndefined=this.isUndefined;
            (isUndefined(isCover))&&(isCover=true);
            for(var name in source){
                if(isCover||isUndefined(destination[name])){
                    destination[name]=source[name];
                }
            
            }
            return destination;
        };
        /**
         *原型继承对象
        **/
        this.inherit=function(child,parent){
            var func=function(){};
            func.prototype=parent.prototype;
            child.prototype=new func();
            child.prototype.constructor=child;
            child.prototype.parent=parent;
        };
    
});

The above is the detailed content of HTML5 game framework cnGameJS development record - code example of core function module. 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
Mastering Microdata: A Step-by-Step Guide for HTML5Mastering Microdata: A Step-by-Step Guide for HTML5May 14, 2025 am 12:07 AM

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

What's New in HTML5 Forms? Exploring the New Input TypesWhat's New in HTML5 Forms? Exploring the New Input TypesMay 13, 2025 pm 03:45 PM

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment