要在遊戲前加上開始的畫面
就先在圖片載入的時後加上開始畫面的 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');
}
}
因為結束和開始的畫面是共用 game_start()
所以結束後還可以再按空白就會再開始
提供範例連結可以玩玩看
https://jsbin.com/yiqivuf/