웹 프론트엔드 H5 튜토리얼 HTML5 게임 프레임워크 cnGameJS 개발 기록 - 기본 그래픽 모듈

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

Mar 24, 2017 pm 04:16 PM

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

HTML의 테이블 테두리 HTML의 테이블 테두리 Sep 04, 2024 pm 04:49 PM

HTML의 테이블 테두리 안내. 여기에서는 HTML의 테이블 테두리 예제를 사용하여 테이블 테두리를 정의하는 여러 가지 방법을 논의합니다.

HTML의 중첩 테이블 HTML의 중첩 테이블 Sep 04, 2024 pm 04:49 PM

HTML의 Nested Table에 대한 안내입니다. 여기에서는 각 예와 함께 테이블 내에 테이블을 만드는 방법을 설명합니다.

HTML 여백-왼쪽 HTML 여백-왼쪽 Sep 04, 2024 pm 04:48 PM

HTML 여백-왼쪽 안내. 여기에서는 HTML margin-left에 대한 간략한 개요와 코드 구현과 함께 예제를 논의합니다.

HTML 테이블 레이아웃 HTML 테이블 레이아웃 Sep 04, 2024 pm 04:54 PM

HTML 테이블 레이아웃 안내. 여기에서는 HTML 테이블 레이아웃의 값에 대해 예제 및 출력 n 세부 사항과 함께 논의합니다.

HTML 입력 자리 표시자 HTML 입력 자리 표시자 Sep 04, 2024 pm 04:54 PM

HTML 입력 자리 표시자 안내. 여기서는 코드 및 출력과 함께 HTML 입력 자리 표시자의 예를 논의합니다.

HTML에서 텍스트 이동 HTML에서 텍스트 이동 Sep 04, 2024 pm 04:45 PM

HTML에서 텍스트 이동 안내. 여기서는 Marquee 태그가 구문과 함께 작동하는 방식과 구현할 예제에 대해 소개합니다.

HTML 정렬 목록 HTML 정렬 목록 Sep 04, 2024 pm 04:43 PM

HTML 순서 목록에 대한 안내입니다. 여기서는 HTML Ordered 목록 및 유형에 대한 소개와 각각의 예에 대해서도 설명합니다.

HTML 온클릭 버튼 HTML 온클릭 버튼 Sep 04, 2024 pm 04:49 PM

HTML onclick 버튼에 대한 안내입니다. 여기에서는 각각의 소개, 작업, 예제 및 다양한 이벤트의 onclick 이벤트에 대해 설명합니다.

See all articles