簡體   English   中英

畫布在事件監聽器上消失

[英]Canvas disappearing on event listener

我正在嘗試創建一個在按鍵上移動以進行乒乓球游戲的矩形,當我按下鍵時,左直接消失..任何想法如何解決問題? 這非常重要..代碼是用vanilla javascript編寫的,所以請不要寫jQuery ..

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pong</title> <script type="text/javascript"> var x = 100; var y = 100; var xmoveFirst = 720; var ymoveFirst = 0; var xmoveSecond = 30 ; var ymoveSecond = 0; function canvas() { var can = document.getElementById('theCanvas'); can.style.backgroundColor = "black"; var ctx = can.getContext('2d'); //first player ctx.fillStyle="white"; ctx.fillRect(xmoveFirst,ymoveFirst,5,75); //second player ctx.fillStyle = 'white'; ctx.fillRect(xmoveSecond,ymoveSecond,5,75); //first player move function moveFirst(eFirst) { ctx.clearRect(0,0,750,750); //clear rects if (eFirst.keyCode == 40) { ymoveFirst+=25; console.log("first,"+ymoveFirst); } else if (eFirst.keyCode == 38) { ymoveFirst-=25; console.log("first,"+ymoveFirst); } ctx.fillStyle="white"; ctx.fillRect(xmoveFirst,ymoveFirst,5,75); ctx.fillRect(xmoveSecond,ymoveSecond,5,75); } var first = document.onkeydown = moveFirst; //second player move function moveSecond(eSecond) { ctx.clearRect(0,0,750,750); if (eSecond.keyCode == 83) { ymoveSecond+=25; console.log("second,"+ymoveSecond); } else if (eSecond.keyCode == 87) { ymoveSecond-=25; } ctx.fillStyle="white"; ctx.fillRect(xmoveFirst,ymoveFirst,5,75); ctx.fillRect(xmoveSecond,ymoveSecond,5,75); console.log("second,"+ymoveSecond) } var second = document.onkeydown = moveSecond; } 83,87 </script> </head> <body onload="canvas()"> <canvas id="theCanvas" width="750" height="750"></canvas> </body> </html> 

這一行: can.width=can.width; 重置畫布寬度。

更改畫布大小(寬度或高度)時,清除畫布(使所有內容變為黑色)。 在這一行之后,你只是重新繪制最右邊的槳,所以左邊的槳仍然缺失。

如果你想讓它回來,你還需要重新繪制最左邊的槳。 這是修改后的moveRight()函數:

function moveRight(eFirst) {
  if (eFirst.keyCode==40) {
    ymoveFirst+=25;
    console.log(ymoveFirst);
  }

  else if (eFirst.keyCode==38) {
    ymoveFirst-=25;
    console.log(ymoveFirst);
  }
  can.width=can.width;
  ctx.fillStyle="white";

  // Redraw BOTH paddles
  ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
  ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
}

另外,替換

  • document.onkeydown = moveFirst; document.onkeydown = moveSecond;

  • document.addEventListener("keydown", moveFirst); ,和document.addEventListener("keydown", moveSecond);

目前,您正在使用document.onkeydown = moveSecond;覆蓋第一個偵聽document.onkeydown = moveSecond; 通過使用addEventListener ,您不會覆蓋已存在的那些。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM