캔버스에 스프라이트를 그리는 함수를 어떻게 만들 수 있습니까?

A. 엘자 하비

나는 기능을 만들 필요가 sprite()canvas에서 javascript내가 스프라이트를 만들려면이 코드이 있습니다 :

var width = 40,
    height = 28,
    frames = 2,

    currentFrame = 0,

    canvas = document.getElementById("myCanvas");
    ctx = canvas.getContext("2d");
    image = new Image()
    image.src = 'http://s28.postimg.org/k90gybbtl/bird_Sprite.png';

var draw = function(){
    ctx.clearRect(0, 0, width, height);
    ctx.drawImage(image, 0, height * currentFrame, width, height, 0, 0, width, height);

    if (currentFrame == frames) {
      currentFrame = 0;
    } else {
      currentFrame++;
    }
}

setInterval(draw, 120);

간단한 게임에 대한 또 다른 코드가 있습니다.

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myUpBtn = new component(canvasWidth, canvasHeight, "rgba(0, 0, 0, 0)", 0, 0); 
    myGameArea.start();
}

function component(width, height, color, x, y, type) {
    this.type = type;
    if (type == "image") {
      this.image = new Image();
      this.image.src = color;
    }
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else {
                if (type == "image") {
                    ctx.drawImage(this.image, 
                    this.x, 
                    this.y,
                    this.width, this.height);
                } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
            }
        }
    }
        this.clicked = function() {
        var mytop = this.y;

        var clicked = true;
        if (mytop > myGameArea.y) {
            clicked = false;
        }
        return clicked;
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
} // https://www.w3schools.com/graphics/game_images.asp

등 ... 이제 문제는 ...

두 개의 코드를 함께 만들 수 없습니다

누구든지 나를 도울 수 있습니까?

감사합니다 :)

almcd

다음 코드는 W3 Schools의 게임 코드에 스프라이트를 추가합니다.

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(40, 28, "red", 10, 120, "sprite");
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0;
        this.interval = setInterval(updateGameArea, 20);
        },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;

    if (type === "sprite") {
        this.currentFrame = 0;
        this.frames = 2;
        this.tickCount = 0;
        this.ticksPerFrame = 4;
        this.image = new Image();
        this.image.src = 'http://s28.postimg.org/k90gybbtl/bird_Sprite.png';
    }

    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else if (this.type == "sprite") {
            if (this.tickCount > this.ticksPerFrame) {
                ctx.drawImage(this.image, 0, this.height * this.currentFrame, this.width, this.height, this.x, this.y, this.width, this.height);

                this.tickCount = 0;

                if (this.currentFrame == this.frames) {
                    this.currentFrame = 0;
                } else {
                    this.currentFrame++;
                }
            } else {
                ctx.drawImage(this.image, 0, this.height * this.currentFrame, this.width, this.height, this.x, this.y, this.width, this.height);
                this.tickCount++;
            }
        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

function updateGameArea() {
    var x, height, gap, minHeight, maxHeight, minGap, maxGap;
    for (i = 0; i < myObstacles.length; i += 1) {
        if (myGamePiece.crashWith(myObstacles[i])) {
            return;
        } 
    }
    myGameArea.clear();
    myGameArea.frameNo += 1;
    if (myGameArea.frameNo == 1 || everyinterval(150)) {
        x = myGameArea.canvas.width;
        minHeight = 20;
        maxHeight = 200;
        height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
        minGap = 50;
        maxGap = 200;
        gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
        myObstacles.push(new component(10, height, "green", x, 0));
        myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
    }
    for (i = 0; i < myObstacles.length; i += 1) {
        myObstacles[i].x += -1;
        myObstacles[i].update();
    }
    myScore.text="SCORE: " + myGameArea.frameNo;
    myScore.update();
    myGamePiece.newPos();
    myGamePiece.update();
}

function everyinterval(n) {
    if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
    return false;
}

function accelerate(n) {
    myGamePiece.gravity = n;
}
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
}
<body onload="startGame()">
  <br>
  <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
  <p>Use the ACCELERATE button to stay in the air</p>
  <p>How long can you stay alive?</p>
</body>

요약해서 말하자면:

  • component함수 내에서 type매개 변수가 다음과 같이 설정된 경우 스프라이트 애니메이션을 처리하기 위해 변수를 초기화합니다.sprite
  • update함수 내에서 4 번째 update호출 될 때마다 스프라이트 애니메이션의 다음 프레임 만 그립니다 . 이렇게하면 스프라이트 애니메이션이 빠르게 재생되지 않습니다.
  • 그런 다음 currentFrame원래 코드에서 이전과 동일하게 개수 를 늘리거나 재설정합니다.
  • 스프라이트 애니메이션에서 다음 프레임을 표시 할 준비가되지 않은 경우 기존 프레임을 다시 표시합니다.

더 나아가려면 스프라이트가에서 핵심 기능을 상속하는 별도의 "클래스"가되도록 내 솔루션을 리팩토링하는 것이 component좋습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

jquery로 캔버스에 도구를 어떻게 만들 수 있습니까?

분류에서Dev

캔버스의 루프에 별 행을 어떻게 만들 수 있습니까?

분류에서Dev

Typescript에서 프로그래밍 방식으로 클래스 함수를 어떻게 만들 수 있습니까?

분류에서Dev

출력 스트림에 인쇄하는 일반 함수를 어떻게 만들 수 있습니까?

분류에서Dev

재정의 된 함수를 사용하는 비 멤버 함수를 어떻게 만들 수 있습니까?

분류에서Dev

glsl에서 그라디언트 구를 어떻게 만들 수 있습니까?

분류에서Dev

이름에 변수가있는 여러 함수를 어떻게 만들 수 있습니까?

분류에서Dev

마커 스트라이크 효과를 어떻게 만들 수 있습니까?

분류에서Dev

Fortran 90에서 원형 그리드를 어떻게 만들 수 있습니까?

분류에서Dev

캔버스에서 재귀 lineTo 호출에서 애니메이션을 어떻게 만들 수 있습니까?

분류에서Dev

그림자가있는 레이블 텍스트를 어떻게 만들 수 있습니까?

분류에서Dev

5로 세는 스크립트를 어떻게 만들 수 있습니까?

분류에서Dev

5로 세는 스크립트를 어떻게 만들 수 있습니까?

분류에서Dev

범용 페이징 스플리터를 어떻게 만들 수 있습니까?

분류에서Dev

constexpr 함수는 consteval 함수에서 constexpr 객체를 만들 수 있지만 constexpr 함수는 어떻게 consteval 함수를 사용할 수 없습니까?

분류에서Dev

스크립트를 트리거하는 버튼을 어떻게 만들 수 있습니까?

분류에서Dev

이 함수는 어떻게 만들 수 있습니까?

분류에서Dev

클래스 이름에 변수 이름이있는 클래스를 어떻게 만들 수 있습니까?

분류에서Dev

Python 스크립트를 시작하는 Linux 백그라운드 프로세스 (c)를 어떻게 만들 수 있습니까?

분류에서Dev

C ++ 프레스 스페이스 바를 어떻게 만들 수 있습니까?

분류에서Dev

문자열에서 배열 트리를 어떻게 만들 수 있습니까?

분류에서Dev

웹 페이지 플러그인을 만들기 위해 코드를 리버스 엔지니어링 할 때 특정 요소가 이벤트를 수신 할 때 어떤 함수가 호출되는지 어떻게 알 수 있습니까?

분류에서Dev

C #에서 Microsoft Powerpacks 캔버스를 어떻게 업데이트 / 다시 그릴 수 있습니까?

분류에서Dev

어떻게 BufferedImage를 "흐리게"만들 수 있습니까?

분류에서Dev

주어진 텍스트 파일에서 읽는 프로그램을 어떻게 만들 수 있습니까?

분류에서Dev

Android이 EditText의 그라디언트를 어떻게 만들 수 있습니까?

분류에서Dev

내 bashrc에서 로컬 함수를 어떻게 만들 수 있습니까?

분류에서Dev

PHP에서 pow와 같은 함수를 어떻게 만들 수 있습니까?

분류에서Dev

끝없는 양면 스크롤 recyclerView를 어떻게 만들 수 있습니까?

Related 관련 기사

  1. 1

    jquery로 캔버스에 도구를 어떻게 만들 수 있습니까?

  2. 2

    캔버스의 루프에 별 행을 어떻게 만들 수 있습니까?

  3. 3

    Typescript에서 프로그래밍 방식으로 클래스 함수를 어떻게 만들 수 있습니까?

  4. 4

    출력 스트림에 인쇄하는 일반 함수를 어떻게 만들 수 있습니까?

  5. 5

    재정의 된 함수를 사용하는 비 멤버 함수를 어떻게 만들 수 있습니까?

  6. 6

    glsl에서 그라디언트 구를 어떻게 만들 수 있습니까?

  7. 7

    이름에 변수가있는 여러 함수를 어떻게 만들 수 있습니까?

  8. 8

    마커 스트라이크 효과를 어떻게 만들 수 있습니까?

  9. 9

    Fortran 90에서 원형 그리드를 어떻게 만들 수 있습니까?

  10. 10

    캔버스에서 재귀 lineTo 호출에서 애니메이션을 어떻게 만들 수 있습니까?

  11. 11

    그림자가있는 레이블 텍스트를 어떻게 만들 수 있습니까?

  12. 12

    5로 세는 스크립트를 어떻게 만들 수 있습니까?

  13. 13

    5로 세는 스크립트를 어떻게 만들 수 있습니까?

  14. 14

    범용 페이징 스플리터를 어떻게 만들 수 있습니까?

  15. 15

    constexpr 함수는 consteval 함수에서 constexpr 객체를 만들 수 있지만 constexpr 함수는 어떻게 consteval 함수를 사용할 수 없습니까?

  16. 16

    스크립트를 트리거하는 버튼을 어떻게 만들 수 있습니까?

  17. 17

    이 함수는 어떻게 만들 수 있습니까?

  18. 18

    클래스 이름에 변수 이름이있는 클래스를 어떻게 만들 수 있습니까?

  19. 19

    Python 스크립트를 시작하는 Linux 백그라운드 프로세스 (c)를 어떻게 만들 수 있습니까?

  20. 20

    C ++ 프레스 스페이스 바를 어떻게 만들 수 있습니까?

  21. 21

    문자열에서 배열 트리를 어떻게 만들 수 있습니까?

  22. 22

    웹 페이지 플러그인을 만들기 위해 코드를 리버스 엔지니어링 할 때 특정 요소가 이벤트를 수신 할 때 어떤 함수가 호출되는지 어떻게 알 수 있습니까?

  23. 23

    C #에서 Microsoft Powerpacks 캔버스를 어떻게 업데이트 / 다시 그릴 수 있습니까?

  24. 24

    어떻게 BufferedImage를 "흐리게"만들 수 있습니까?

  25. 25

    주어진 텍스트 파일에서 읽는 프로그램을 어떻게 만들 수 있습니까?

  26. 26

    Android이 EditText의 그라디언트를 어떻게 만들 수 있습니까?

  27. 27

    내 bashrc에서 로컬 함수를 어떻게 만들 수 있습니까?

  28. 28

    PHP에서 pow와 같은 함수를 어떻게 만들 수 있습니까?

  29. 29

    끝없는 양면 스크롤 recyclerView를 어떻게 만들 수 있습니까?

뜨겁다태그

보관