HTML5 게임 프레임워크 cnGameJS 개발 기록 - 기본 그래픽 모듈

黄舟
풀어 주다: 2017-03-24 16:16:02
원래의
1381명이 탐색했습니다.

1. 기능

이 모듈도 매우 간단하며 주로 직사각형, 원, 텍스트의 세 가지 기본 그래픽 그리기를 포함합니다. Constructor 패턴으로 각 이미지를 캡슐화합니다. 예를 들어 직사각형 객체를 그려야 하는 경우 먼저 new 직사각형 객체를 생성합니다. 그리려면 객체 그리기 메서드를 호출하세요. 예를 들면 다음과 같습니다.

var rect=new cnGame.shape.Rect();
rect.draw();
로그인 후 복사

2.

구현 이 모듈에는 세 개의 그래픽 객체가 포함되어 있으므로 각 생성자는 Drawing, 이동, 회전, 크기 조정 등 세 가지 개체에는 유사한 메서드가 많이 있으므로 설명하기 위해 직사각형 개체를 예로 들어 먼저 생성자를 살펴보겠습니다.

/**
     *矩形对象
    **/                                        
    var rect=function(options){
        if(!(this instanceof arguments.callee)){
            return new arguments.callee(options);
        }
        this.init(options);
    }
로그인 후 복사

주의해야 할 점은 입니다. 이 함수를 생성자로 호출하지 않으면 새로운 생성자를 반환하므로 함수는 항상 생성자로 호출되어 생성된 직사각형 객체를 반환합니다. 그런 다음 초기화를 위해 init를 호출합니다.

또한 개체마다 속성이 다르지만 해당 개체에 대한 기본 개체도 설정해야 합니다. 여기서는 코어 모듈의 확장 기능을 사용하여 사용자가 설정한 매개변수를 기본 개체의 매개변수와 병합해야 합니다.

/**
             *默认值对象
            **/                                                
            var defaultObj={
                x:0,
                y:0,
                width:100,
                height:100
                
            };
            options=options||{};
            options=cg.core.extend(defaultObj,options);
로그인 후 복사

직사각형의 경우 특별한 점은 정점이 4개 있다는 것입니다. x 및 y 좌표를 저장하는 것 외에도 오른쪽 정점과 하단 정점을 저장하여 향후 직사각형 충돌 감지를 용이하게 합니다. 이 기능도 매우 간단합니다. , 너비, 높이, xy 및 바닥을 기준으로 오른쪽을 계산하는 것입니다.

/**
     *更新right和bottom
    **/    
    var resetRightBottom=function(elem){
        elem.right=elem.x+elem.width;
        elem.bottom=elem.y+elem.height;    
    }
로그인 후 복사

직사각형에 위치 및 크기 매개변수가 있으면 이전 매개변수에 따라 그릴 수 있습니다(채우기 및 획 모드 사용). 각각):

/**
         *绘制矩形
        **/    
        draw:function(style,isFill){
            var context=cg.context;
            (cg.core.isUndefined(isFill))&&(isFill=true);
            if(isFill){
                context.fillStyle = style;
                context.fillRect(this.x, this.y, this.width, this.height);
            }
            else{
                context.strokeStyle = style;
                context.strokeRect(this.x, this.y, this.width, this.height);
            }
            
              return this;
            
        }
로그인 후 복사

또한 개발이나 테스트를 용이하게 하기 위해 객체는 자체 매개변수를 변경할 수 있는 다양한 다른 방법도 제공합니다.

1.move: 직사각형을 특정 거리만큼 이동합니다.

2.moveTo: 사각형을 특정 거리만큼 이동합니다.

3.resize: 사각형을 특정 크기로 변경

4.resizeTo: 변경 특정 크기의 직사각형

이 메소드는 최종적으로 이를 반환합니다. 메소드가 체인 호출을 지원하도록 합니다.

이 모듈도 비교적 간단하므로 자세히 설명하지 않겠습니다. 마지막으로 모듈의 모든 소스 코드가 제공됩니다:

/**
 *
 *canvas基本形状对象
 *
**/
cnGame.register("cnGame.shape",function(cg){

    /**
     *更新right和bottom
    **/    
    var resetRightBottom=function(elem){
        elem.right=elem.x+elem.width;
        elem.bottom=elem.y+elem.height;    
    }
    /**
     *矩形对象
    **/                                        
    var rect=function(options){
        if(!(this instanceof arguments.callee)){
            return new arguments.callee(options);
        }
        this.init(options);
    }
    rect.prototype={
        /**
         *初始化
        **/
        init:function(options){
            /**
             *默认值对象
            **/                                                
            var defaultObj={
                x:0,
                y:0,
                width:100,
                height:100,
                style:"red",
                isFill:true
                
            };
            options=options||{};
            options=cg.core.extend(defaultObj,options);
            this.setOptions(options);
        
            resetRightBottom(this);
        },
        /**
         *绘制矩形
        **/    
        setOptions:function(options){
            this.x=options.x;
            this.y=options.y;
            this.width=options.width;
            this.height=options.height;    
            this.style=options.style;
            this.isFill=this.isFill;
        },
        /**
         *绘制矩形
        **/    
        draw:function(){
            var context=cg.context;
            if(this.isFill){
                context.fillStyle = this.style;
                context.fillRect(this.x, this.y, this.width, this.height);
            }
            else{
                context.strokeStyle = this.style;
                context.strokeRect(this.x, this.y, this.width, this.height);
            }
            
              return this;
            
        },
        /**
         *将矩形移动一定距离
        **/    
        move:function(dx,dy){
            dx=dx||0;
            dy=dy||0;
            this.x+=dx;
            this.y+=dy;
            resetRightBottom(this);
            return this;
        },
        /**
         *将矩形移动到特定位置
        **/    
        moveTo:function(x,y){
            x=x||this.x;
            y=y||this.y;
            this.x=x;
            this.y=y;
            resetRightBottom(this);
            return this;
        },
        /**
         *将矩形改变一定大小
        **/    
        resize:function(dWidth,dHeight){
            dWidth=dWidth||0;
            dHeight=dHeight||0;
            this.width+=dWidth;
            this.height+=dHeight;
            resetRightBottom(this);
            return this;
            
        },
        /**
         *将矩形改变到特定大小
        **/    
        resizeTo:function(width,height){
            width=width||this.width;
            height=height||this.height;
            this.width=width;
            this.height=height;
            resetRightBottom(this);
            return this;
        }
    }
    
    /**
     *圆形对象
    **/        
    var circle=function(options){
        if(!(this instanceof arguments.callee)){
            return new arguments.callee(options);
        }
        this.init(options);
    }
    circle.prototype={
        /**
         *初始化
        **/
        init:function(options){
            /**
             *默认值对象
            **/
            var defaultObj={
                x:100,
                y:100,
                r:100,
                startAngle:0,
                endAngle:Math.PI*2,
                antiClock:false,
                style:"red",
                isFill:true
            };
            options=options||{};
            options=cg.core.extend(defaultObj,options);
            this.setOptions(options);
        
        },
        /**
         *设置参数
        **/
        setOptions=function(options){
            this.x=options.x;
            this.y=options.y;
            this.r=options.r;
            this.startAngle=options.startAngle;
            this.endAngle=options.endAngle;
            this.antiClock=options.antiClock;
            this.isFill=options.isFill;
            this.style=options.style;
        },
        /**
         *绘制圆形
        **/
        draw:function(){
            var context=cg.context;
            context.beginPath();
            context.arc(this.x,this.y,this.r,this.startAngle,this.endAngle,this.antiClock);
            context.closePath();
            if(this.isFill){
                context.fillStyle=this.style;
                context.fill();
            }
            else{
                context.strokeStyle=this.style;
                context.stroke();
            }
            
        },
        /**
         *将圆形移动一定距离
        **/    
        move:function(dx,dy){
            dx=dx||0;
            dy=dy||0;
            this.x+=dx;
            this.y+=dy;
            return this;
        },
        /**
         *将圆形移动到特定位置
        **/    
        moveTo:function(x,y){
            x=x||this.x;
            y=y||this.y;
            this.x=x;
            this.y=y;
            return this;
        },
        /**
         *将圆形改变一定大小
        **/    
        resize:function(dr){
            dr=dr||0;
            this.r+=dr;
            return this;
            
        },
        /**
         *将圆形改变到特定大小
        **/    
        resizeTo:function(r){
            r=r||this.r;
            this.r=r;
            return this;
        }    
    }
    /**
     *将圆形改变到特定大小
    **/    
    var text=function(text,options){
        if(!(this instanceof arguments.callee)){
            return new arguments.callee(text,options);
        }
        this.init(text,options);
    
    }
    text.prototype={
        /**
         *初始化
        **/
        init:function(text,options){
            /**
             *默认值对象
            **/
            var defaultObj={
                x:100,
                y:100,
                style:"red",
                isFill:true
                
            };
            options=options||{};
            options=cg.core.extend(defaultObj,options);
            this.setOptions(options);
            this.text=text;        
        },
        /**
        *绘制
        **/
        draw:function(){
            var context=cg.context;
            (!cg.core.isUndefined(this.font))&&(context.font=this.font);
            (!cg.core.isUndefined(this.textBaseline))&&(context.textBaseline=this.textBaseline);
            (!cg.core.isUndefined(this.textAlign))&&(context.textAlign=this.textAlign);
            (!cg.core.isUndefined(this.maxWidth))&&(context.maxWidth=this.maxWidth);
            if(this.isFill){
                context.fillStyle=this.style;
                this.maxWidth?context.fillText(this.text,this.x,this.y,this.maxWidth):context.fillText(this.text,this.x,this.y);
            }
            else{
                context.strokeStyle=this.style;
                this.maxWidth?context.strokeText(this.text,this.x,this.y,this.maxWidth):context.strokeText(this.text,this.x,this.y);
            }
        },
        /**
        *设置参数
        **/
        setOptions:function(options){
            this.x=options.x||this.x;
            this.y=options.y||this.y;
            this.maxWidth=options.maxWidth||this.maxWidth;
            this.font=options.font||this.font;
            this.textBaseline=options.textBaseline||this.textBaseline;
            this.textAlign=options.textAlign||this.textAlign;
            this.isFill=options.isFill||this.isFill;
            this.style=options.style||this.style;
            
        }
    }
    
    this.Text=text;
    this.Rect=rect;
    this.Circle=circle;
    
});
로그인 후 복사

위 내용은 HTML5 게임 프레임워크 cnGameJS 개발 기록 - 기본 그래픽 모듈의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!