2012-07-05 4 views
3

이 코드로 캔버스에 이미지를 그립니다. 캔버스에 이미지를 성공적으로 그립니다. 캔버스에서 이미지를 옮길 것입니다. 난 내 키보드의 오른쪽 키를 누르면 i가 증가합니다 확인은 x 왼쪽 키는 내가 X 좌표 감소시킵니다 누르면되지만 이미지가 어떻게 이동하는 캔버스에html5의 키보드 화살표 키를 사용하여 캔버스에서 이미지를 이동하는 방법

player = new Image(); 
player.src = "game_character.png"; 
context.drawImage(player,player.x * wallDim + wallDim ,player.y * wallDim + wallDim ,50,50); 

를 이동하지 않을 경우 이미지의 좌표 캔버스상의 이미지

var handleInput = function(event, keyState) { 
     switch(event.which) { 
       case 37: { // Left Arrow 
        keyDown.arrowLeft = keyState; 
        break; 
       } 
       case 38: { // Up Arrow 
        keyDown.arrowUp = keyState; 
        break; 
       } 
       case 39: { // Right Arrow 
        keyDown.arrowRight = keyState; 
        break; 
       } 
       case 40: { // Down Arrow 
        keyDown.arrowDown = keyState; 
        break; 
       } 
     } 
    } 

    /** 
    * physics 
    * 
    * This function contains the basic logic for the maze. 
    */ 
    var physics = function() { 
     console.log("physics "); 
     console.log("first condition "+keyDown.arrowRight +player.x+1); 
     if(keyDown.arrowLeft && player.x-1 >= 0 && map[player.y][player.x-1] != 1) { 
       player.x--; 
       redraw = true; 
     } 

     if(keyDown.arrowUp && player.y-1 >= 0 && map[player.y-1][player.x] != 1) { 
       player.y--; 
       redraw = true; 
     } 

     if(keyDown.arrowRight && player.x+1 < map[0].length && map[player.y][player.x+1] != 1) { 
       console.log("arrow right"); 
       player.x++; 
       redraw = true; 
     } 

     if(keyDown.arrowDown && player.y+1 < map.length && map[player.y+1][player.x] != 1) { 
       player.y++; 
       redraw = true; 
     } 
     if(keyDown.arrowRight && player.x+1 >= map[0].length) 
     { 
      player.x++; 
      document.getElementById("canvas_div").style.display="none"; 
      document.getElementById("end_screen_div").style.display="block"; 
      //alert("completed"); 
     } 
    } 

    /** 
    * draw 
    * 
    * This function simply draws the current state of the game. 
    */ 
    var draw = function() { 

     // Don't redraw if nothing has changed 
     if(!redraw) 
       return; 

     context.clearRect(0, 0, cols, rows); 
     context.beginPath(); 

     // Draw the maze 
     for(var a = 0; a < rows; a++) { 
       for(var b = 0; b < cols; b++) { 
        switch(map[a][b]) { 
          case C.EMPTY: context.fillStyle = colors.empty; break; 
          case C.WALL: context.fillStyle = colors.wall; break; 
        } 

         context.fillRect(b * wallDim, a * wallDim, wallDim, wallDim); // x, y, width, height 
       } 
     } 

     // Draw the player 
    /* context.fillStyle = colors.player; 
     context.arc(
       player.x * wallDim + wallDim/2, // x position 
       player.y * wallDim + wallDim/2, // y position 
       wallDim/2, // Radius 
       0, // Starting angle 
       Math.PI * 2, // Ending angle 
       true // antiClockwise 
     );*/ 


    player = new Image(); 
    player.src = "game_character.png"; 

    context.drawImage(player,player.x * wallDim + wallDim ,player.y * wallDim + wallDim ,50,50); 

    var firstplayer=new Image(); 
    firstplayer.src="top_character01.png"; 

    context.drawImage(firstplayer,680,0,60,60); 

    var secondplayer= new Image(); 
    secondplayer.src="top_character02.png"; 

    context.drawImage(secondplayer,750,0,60,60); 

    context.fill(); 
    context.closePath(); 

     redraw = false; 
    } 
+0

더 많은 코드를 보여줄 수 있습니까? 키아 업 감지 및 다시 그리기 호출은 최소한? –

+0

어떤 모양을 사용하더라도 완벽하게 움직이지만 이미지가 움직이지 않는 경우 – deve1

답변

0

당신의 그림에서 thod를 사용할 때마다 플레이어를 다시 초기화합니다.

따라서 이벤트 처리기로 수정 한 player.x를 지울 수 있습니다.

플레이어를 그리기 기능 외부에서 한 번만 초기화해야합니다. 이 같은 초기화를 이동할 수 있습니다

var player = new Image(); 
player.src = "game_character.png"; 
var draw = function() { 

그리기 함수 내에서 player.src = "game_character.png";를 호출 할 필요가 전혀 없습니다.

일반적으로 애니메이션을 다룰 때 최대한 빨리해야하는 그리기 기능에서 가능한 모든 것을 제거하십시오.

+0

해결책은 무엇입니까? – deve1

+0

플레이어를 한 번만 정의하고 만듭니다 (그리기 기능 제외). 편집을 참조하십시오. –

+0

그리기 메서드 외부에서 캔버스에 이미지를 그리지 않는다고 선언하면 – deve1

0

매번 캔버스를 다시 그려야합니다. 이런 식으로 뭔가 :

function init() 
{ 
    canvas = document.getElementById("canvas"); 
    context = canvas.getContext("2d"); 

    x = canvas.width/2; //align to centre of the screen 
    y = canvas.height/2; //same as above 

    speed = 5; //speed for the player to move at 

    width = 50; //width of the player 
    height = 50; //height of the player 

    playerimage = new Image(); 
    playerimage.src = "path/to/image/for/player"; //path to the image to use for the player 

    canvas.addEventListener("keypress", update); 
} 

function update(event) 
{ 
    if (event.keyCode == 38) 
    { 
     y -= speed; //going up 
    } 
    if (event.keyCode == 40) 
    { 
     y += speed; //going down 
    } 
    if (event.keyCode == 37) 
    { 
     x -= speed; //going left 
    } 
    if (event.keyCode == 39) 
    { 
     x += speed; //going right 
    } 
    render(); 
} 

function render() 
{ 
    context.clearRect(0, 0, canvas.width, canvas.height); 
    context.drawImage(playerimage, x, y, width, height); 
} 

나는 그것을 테스트하지 않았습니다, 그래서 작동하고 여기 저기 몇 가지 실수가있을 수 있는지 모르겠어요. 그래도 작동합니다! 그밖에 아무것도, (희망 적으로) 당신이 그것에 관하여 갈 수있는 1 가지의 방법의 아이디어를 줄 것이다.

관련 문제