2017-09-29 3 views
2

필자는 타일 기반의 플랫폼 게임을 사용하고 있는데, 타일은 현재 fillRect 함수를 사용하여 색상이있는 사각형으로 렌더링됩니다. 대신 사각형을 렌더링하는 데 사용하려는 스프라이트 시트가 있습니다. 각 타일과 스프라이트는 너비와 높이가 각각 32 픽셀입니다. 나는 이미지를자를 때로드 기능이 필요하지만, 자르기를해야하고 스프라이트를 60 프레임 초당 그릴 필요가 있는지 확신 할 수 없다. Heres는 내 JS 바이올린 - https://jsfiddle.net/LsLpyn8p/4/html5 캔버스에 스프라이트가 표시되지 않습니다.

또는 아래의 코드 :

 var canvas = document.getElementById('canvas'); 
    var ctx = canvas.getContext('2d'); 

    var width = 6; 
    var height = 3; 
    var tileSize = 32; 

    var counter = 0; 
    var playerUp = false; 

    setInterval(gameLoop, 1000/30); 

    function gameLoop() { 
     ctx.fillStyle = "white"; 
     ctx.fillRect(0, 0, canvas.width, canvas.height); 

     for (var y = 0; y < height; y++) { 
      for (var x = 0; x < width; x++) { 
       posX = (x * tileSize) + 1 * x; 
       posY = (y * tileSize) + 1 * y; 

       //  ctx.fillStyle = "green"; 
       // ctx.fillRect(posX, posY, tileSize, tileSize); 
       var spriteSheet = new Image(); 
       spriteSheet.src = 'https://pasteboard.co/GMAwgYX.png'; 

       ctx.drawImage(spriteSheet, 0, 4 * tileSize, tileSize, tileSize, posX, posY, tileSize, tileSize); 
      } 
     } 

     ctx.fillStyle = "red"; 
     ctx.fillRect(50, counter, tileSize, tileSize); 

     if (playerUp == true) { 
      counter--; 
     } else { 
      counter++; 
     } 

     if (counter == 100) { 
      playerUp = true; 
     } else if (counter == 0) { 
      playerUp = false; 
     } 
    } 

어떤 도움이 appricated되어 감사

+0

당신하려면 .src 링크는 죄송하지 IMG https://ibb.co/e5K5Qb –

+0

를 HTML 전합니다 바이올린에 온라인이 필요했지만 지금은 작동하지 않습니다. –

+0

이미지 URL을 'https : // imag'로 변경해야합니다. e.ibb.co/hZe5Qb/levelOne.png'주의 : 이미지가 비동기 적으로로드되므로 이미지를 그릴 때 실제로 이미지가로드되지 않습니다. – MysterX

답변

0

난 당신이 이미지의 컷 아웃 조각을 배치하려는 가정합니다.

이 경우는 4 * 32 = 128

는 X가 SourceImage의 좌표입니다, 4 * tileSize를 가리키는 것은 이미지가 너무 작이 많은 픽셀이없는 128입니다. 예를 들어 10

시작 :

ctx.drawImage(spriteSheet, 0, 10, tileSize, tileSize, posX, posY, tileSize, tileSize); 

jsFiddle

Documentation

void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); 

sx 
The X coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context. 

sy 
The Y coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context. 
관련 문제