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

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으로 문의하세요.
H5 : 웹에서 사용자 경험을 향상시키는 방법H5 : 웹에서 사용자 경험을 향상시키는 방법Apr 19, 2025 am 12:08 AM

H5는 멀티미디어 지원, 오프라인 스토리지 및 성능 최적화로 웹 사용자 경험을 향상시킵니다. 1) 멀티미디어 지원 : H5 및 요소는 개발을 단순화하고 사용자 경험을 향상시킵니다. 2) 오프라인 스토리지 : WebStorage 및 IndexedDB는 오프라인으로 사용하여 경험을 향상시킵니다. 3) 성능 최적화 : 웹 워즈 및 요소는 성능을 최적화하여 대역폭 소비를 줄입니다.

H5 코드 해체 : 태그, 요소 및 속성H5 코드 해체 : 태그, 요소 및 속성Apr 18, 2025 am 12:06 AM

HTML5 코드는 태그, 요소 및 속성으로 구성됩니다. 1. 태그는 컨텐츠 유형을 정의하고 다음과 같은 각도 브래킷으로 둘러싸여 있습니다. 2. 요소는 컨텐츠와 같은 시작 태그, 내용 및 엔드 태그로 구성됩니다. 3. 속성 시작 태그에서 키 값 쌍을 정의하고 기능을 향상시킵니다. 웹 구조를 구축하기위한 기본 단위입니다.

H5 코드 이해 : HTML5의 기본 사항H5 코드 이해 : HTML5의 기본 사항Apr 17, 2025 am 12:08 AM

HTML5는 현대적인 웹 페이지를 구축하는 핵심 기술로 많은 새로운 요소와 기능을 제공합니다. 1. HTML5는 웹 페이지 구조 및 SEO를 향상시키는 의미 론적 요소를 소개합니다. 2. 멀티미디어 요소를 지원하고 플러그인없이 미디어를 포함시킵니다. 3. 양식은 새로운 입력 유형 및 검증 속성을 향상시켜 검증 프로세스를 단순화합니다. 4. 웹 페이지 성능 및 사용자 경험을 향상시키기 위해 오프라인 및 로컬 스토리지 기능을 제공합니다.

H5 코드 : 웹 개발자를위한 모범 사례H5 코드 : 웹 개발자를위한 모범 사례Apr 16, 2025 am 12:14 AM

H5 코드에 대한 모범 사례는 다음과 같습니다. 1. 올바른 문서 선언 및 문자 인코딩 사용; 2. 시맨틱 태그를 사용하십시오. 3. HTTP 요청을 줄입니다. 4. 비동기 부하 사용; 5. 이미지 최적화. 이러한 관행은 웹 페이지의 효율성, 유지 관리 및 사용자 경험을 향상시킬 수 있습니다.

H5 : 웹 표준 및 기술의 발전H5 : 웹 표준 및 기술의 발전Apr 15, 2025 am 12:12 AM

웹 표준과 기술은 현재까지 HTML4, CSS2 및 간단한 JavaScript에서 발전했으며 중대한 개발을 거쳤습니다. 1) HTML5는 캔버스 및 웹 스토리지와 같은 API를 도입하여 웹 응용 프로그램의 복잡성과 상호 작용을 향상시킵니다. 2) CSS3은 애니메이션 및 전환 기능을 추가하여 페이지를보다 효과적으로 만듭니다. 3) JavaScript는 화살표 기능 및 클래스와 같은 Node.js 및 ES6의 최신 구문을 통해 개발 효율 및 코드 가독성을 향상시킵니다. 이러한 변경으로 인해 웹 애플리케이션의 성능 최적화 및 모범 사례의 개발이 촉진되었습니다.

H5는 HTML5의 속기입니까? 세부 사항을 탐색합니다H5는 HTML5의 속기입니까? 세부 사항을 탐색합니다Apr 14, 2025 am 12:05 AM

H5는 HTML5의 약어 일뿐 만 아니라 더 넓은 현대 웹 개발 기술 생태계를 나타냅니다. 1. H5는 HTML5, CSS3, JavaScript 및 관련 API 및 기술을 포함합니다. 2. 그것은 더 풍부하고 대화식이며 부드러운 사용자 경험을 제공하며 여러 장치에서 원활하게 실행할 수 있습니다. 3. H5 기술 스택을 사용하여 반응 형 웹 페이지와 복잡한 대화식 기능을 만들 수 있습니다.

H5 및 HTML5 : 웹 개발에 일반적으로 사용되는 용어H5 및 HTML5 : 웹 개발에 일반적으로 사용되는 용어Apr 13, 2025 am 12:01 AM

H5 및 HTML5는 동일한 것을, 즉 html5를 나타냅니다. HTML5는 HTML의 다섯 번째 버전으로 시맨틱 태그, 멀티미디어 지원, 캔버스 및 그래픽, 오프라인 스토리지 및 로컬 스토리지와 같은 새로운 기능을 제공하여 웹 페이지의 표현성 및 상호 작용성을 향상시킵니다.

H5는 무엇을 언급합니까? 맥락 탐색H5는 무엇을 언급합니까? 맥락 탐색Apr 12, 2025 am 12:03 AM

h5referstohtml5, apivotaltechnologyinwebdevelopment.1) html5introducesnewelements 및 dynamicwebapplications.2) itsupp ortsmultimediawithoutplugins, enovannangeserexperienceacrossdevices.3) SemanticLementsImproveContentsTructUreAndSeo.4) H5'Srespo

See all articles

핫 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경