我可以在对话框中而不是在“警报”中在画布内显示在游戏中获胜或失败后的结果吗?

时间:2019-07-12 13:12:57

标签: javascript html5-canvas

enter image description here我可以在对话框中而不是在使用“警报”的情况下在画布上显示赢或输游戏后的结果吗?

          function collisionDetection() {
  for(var c=0; c<brickColumnCount; c++) {
   for(var r=0; r<brickRowCount; r++) {
    var b = bricks[c][r];
   if(b.status == 1) {
    if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
      dy = -dy;
      b.status = 0;
      score++;
      if(score == brickRowCount*brickColumnCount) {
        alert("YOU WIN, CONGRATS!");
        document.location.reload();
      }
    }
  }
   }
   }  
   }


function draw() {
 ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPaddle();
drawScore();
drawLives();
 collisionDetection();

  if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
  dx = -dx;
  }
 if(y + dy < ballRadius) {
   dy = -dy;
 }
 else if(y + dy > canvas.height-ballRadius) {
   if(x > paddleX && x < paddleX + paddleWidth) {
    dy = -dy;
   }
   else {
     lives--;
     if(!lives) {
     alert("GAME OVER");
     document.location.reload();

我要在对话框中而不是在警报框中显示“恭喜您”和“您输了”行。

1 个答案:

答案 0 :(得分:1)

您可以将多个画布彼此叠加。最下面的一个可以包含游戏区域,最上面的一个可以包含消息。这是一个简单的示例:

const gameCvs = document.getElementById('game');
const gameCtx = gameCvs.getContext('2d');
const dialogCvs = document.getElementById('dialog');
const dialogCtx = dialogCvs.getContext('2d');

function showDialog(message) {
  dialogCtx.clearRect(0, 0, dialogCvs.width, dialogCvs.height);
  dialogCtx.textAlign = 'center';
  dialogCtx.fillText(message, dialogCvs.width / 2, dialogCvs.height / 2);
}

// For demo purposes, click the gameplay canvas to "lose" the game
gameCvs.addEventListener('click', (e) => {
  showDialog('GAME OVER');
  dialogCvs.removeAttribute('hidden');
});

// Click the dialog canvas to hide it
dialogCvs.addEventListener('click', (e) => {
  dialogCvs.setAttribute('hidden', 'hidden');
});
main {
  position: relative;
}

#game {
  background: #11a;
}

#dialog {
  background: rgba(255,255,255,.5);
  position: absolute;
  left: 0;
  top: 0;
}
<main>
  <canvas id="game"></canvas>
  <canvas id="dialog" hidden></canvas>
</main>