iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 30
0
自我挑戰組

學習 canvas 日記系列 第 30

第 30 天 迷宮 五

要在遊戲前加上開始的畫面
https://ithelp.ithome.com.tw/upload/images/20181112/20107496iC4WiyHlBj.jpg
就先在圖片載入的時後加上開始畫面的 function

img.onload = function () {
  canvas.width = img.width;
  canvas.height = img.height;
  ctx.drawImage(img, 0, 0);
  ctx.beginPath();
  ctx.strokeStyle = 'black';
  ctx.lineWidth = '3';
  ctx.strokeRect(0, 0, canvas.width, canvas.height);
  ctx.stroke();

  game_start('開始遊戲')
};

並在 addEventListener 中加入當按下空白就開始遊戲

window.addEventListener('keydown',function(e){
    if(e.code === 'Space'){
        loadMap();
    }
})

function loadMap(){
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(img, 0, 0);
  
    if(canvas.width/16.4 %2 == 0){
    circleStart.x = (canvas.width-4)/2 - 6;
    circleStart.y = 10;
    circlePoint(circleStart.x, circleStart.y, circleStart.r, 'red');
    
    circleEnd.x = (canvas.width-4)/2 + 10;
    circleEnd.y = canvas.height -9;
    circlePoint(circleEnd.x, circleEnd.y, circleEnd.r, 'green');
    
  }else{
    circleStart.x = canvas.width/2;
    circleStart.y = 10;
    circlePoint(circleStart.x, circleStart.y, circleStart.r, 'red');
    circleEnd.x = canvas.width/2;
    circleEnd.y = canvas.height -9;
    circlePoint(circleEnd.x, circleEnd.y, circleEnd.r, 'green');
  }
}

https://i.imgur.com/J31bVpp.gif
因為結束和開始的畫面是共用 game_start()
所以結束後還可以再按空白就會再開始
https://i.imgur.com/JHl74Jz.gif

提供範例連結可以玩玩看
https://jsbin.com/yiqivuf/


上一篇
第 29 天 迷宮 四
系列文
學習 canvas 日記30

尚未有邦友留言

立即登入留言