Home > Web Front-end > H5 Tutorial > body text

HTML5 game framework cnGameJS development record - code example of core function module

黄舟
Release: 2017-03-24 16:05:26
Original
1494 people have browsed it

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)
Copy after login

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;
        }
Copy after login

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(){}});
Copy after login

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);
Copy after login

 


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";
            
        },
Copy after login

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];

    }
Copy after login

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);
                            }
                        }
        })();
Copy after login

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;
        };
    
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!