퐁(PONG)

심민기·2022년 5월 2일
0

웹 개발

목록 보기
28/33

캔버스로 그림 그리기

Js의 캔버스, 그리드를 이용해 그림을 그려, 퐁을 구현해 보자.

캔버스 생성.

문서 가져오기. const { body } = document; 캔버스를 생성. const canvas = document.createElement('canvas'); 2d 컨택스트 생성. const context = canvas.getContext('2d'); 캔버스 크기 const width = 500; const height = 700;

캔버스를 문서에 생성.

// 캔버스 생성.
function createCanvas() {
  canvas.width = width;
  canvas.height = height;
  body.appendChild(canvas);
  renderCanvas();
}

캔버스 랜더링.

캔버스 배경.
context.fillStyle = 'black';
context.fillRect(0,0,width,height);

막대기 색
context.fillStyle = 'white';
플레이어 막대기 (하단)
context.fillRect(paddleBottomX, height - 20, paddleWidth, paddleHeight);
컴퓨터 막대기 (상단)
context.fillRect(paddleTopX, 10, paddleWidth, paddleHeight);

중앙라인(점선)
context.beginPath();
context.setLineDash([4]);
context.moveTo(0, 350);
context.lineTo(500, 350);
context.strokeStyle = 'grey';
context.stroke();

마우스로 막대기 움직이기

canvas.addEventListener('mousemove', (e) => {
    playerMoved = true;
    // Compensate for canvas being centered
    paddleBottomX = e.clientX - canvasPosition - paddleDiff;
    if (paddleBottomX < paddleDiff) {
      paddleBottomX = 0;
    }
    if (paddleBottomX > width - paddleWidth) {
      paddleBottomX = width - paddleWidth;
    }
    // 마우스 숨기기.
    canvas.style.cursor = 'none';
  });

애니메이션

window.requestAnimationFrame(animate);
  • 백그라운드 동작 및 비활성화시 중지(성능 최적화)
  • 최대 1ms(1/1000s)로 제한되며 1초에 60번 동작
  • 다수의 애니메이션에도 각각 타이머 값을 생성 및 참조하지 않고 내부의 동일한 타이머 참조

requestAnimationFrame

게임 오버

// 둘중 하나가 승리점수를 얻은지 확인하고 얻으면 게임 종료.
function gameOver() {
  if (playerScore === winningScore || computerScore === winningScore) {
    isGameOver = true;
    // 승자 결정.
    const winner = (playerScore === winningScore) ? 'Player 1' : 'Computer';
    showGameOverEl(winner);
  }
}

게임오버 화면과 재도전.

function showGameOverEl(winner) {
  // 캔버스 숨기고
  canvas.hidden = true;
  // Container
  gameOverEl.textContent = '';
  gameOverEl.classList.add('game-over-container');
  // 제목
  const title = document.createElement('h1');
  title.textContent = `${winner} 이겼습니다!!`;
  // 재도전 버튼
  const playAgainBtn = document.createElement('button');
  playAgainBtn.setAttribute('onclick', 'startGame()');
  playAgainBtn.textContent = '다시 플레이 하시겠습니까?';
  // 할당.
  gameOverEl.append(title, playAgainBtn);
  body.appendChild(gameOverEl);
}

완성

profile
왕초보

0개의 댓글