簡體   English   中英

使用 Canvas 和 JS 進行乒乓球比賽:每個動作都會重新繪制球?

[英]Pong game with Canvas and JS: ball is redrawn with each movement?

我正在使用 HTML canvas 和 JavaScript 進行典型的 Pong 游戲,但我已經在這個問題上停留了一段時間。 我檢查了類似的 Stackoverflow 問題,但沒有一個答案對我有用。

基本上我有一個 window.onload function 每秒渲染游戲(繪制和移動)。 球會移動,但每次移動都會繪制自己的復制品。 我認為這與我每秒都在渲染這兩件事有關,但我無法弄清楚。

var framesPerSecond = 60;
  setInterval(function() {
    drawGame();
    move();
}, 1000/framesPerSecond);

這是小提琴

謝謝。

Canvas需要在重繪前清除:

canvasContext.clearRect(0, 0, canvas.width, canvas.height);

否則,它將繼續修改現有的 canvas state

查看實際操作 - https://jsfiddle.net/ew2d1quL/2/

您必須從頭開始重新繪制,或者在某處保存另一個畫布/圖像並在繪制游戲的 rest 之前先繪制它

 var canvas; var canvasContext; var printScore = document.createElement("p"); var score = 0; window.onload = function() { canvas = document.getElementById("gameCanvas"); canvasContext = canvas.getContext('2d'); var framesPerSecond = 60; setInterval(function() { drawGame(); move(); }, 1000/framesPerSecond); var leftPaddle = { x: 0, y: (canvas.height/2) - 50, width: 10, height: 100, color: "yellow", score: 0 } var rightPaddle = { x: canvas.width - 10, y: (canvas.height/2) - 50, width: 10, height: 100, color: "yellow", score: 0 } var ball = { x: canvas.width/2, y: canvas.height/2, radius: 9, color: "white", speed: 5, velocityX: 5, velocityY: 5, } function drawGame() { // redraw background canvasContext.fillStyle = 'black'; canvasContext.fillRect(0, 0, canvasContext.canvas.width, canvasContext.canvas.height); drawRect(leftPaddle.x, leftPaddle.y, leftPaddle.width, leftPaddle.height, leftPaddle.color); drawRect(rightPaddle.x, rightPaddle.y, rightPaddle.width, rightPaddle.height, rightPaddle.color); drawCircle(ball.x, ball.y, ball.radius, ball.color); } function drawRect(x, y, w, h, color) { canvasContext.fillStyle = color; canvasContext.fillRect(x, y, w, h); } function drawCircle(x, y, r, color) { canvasContext.fillStyle = color; canvasContext.beginPath(); canvasContext.arc(x, y, r, 0, Math.PI*2, false); canvasContext.fill(); canvasContext.closePath(); } function move() { ball.x += ball.velocityX; ball.y += ball.velocityY; if ( (ball.y + ball.radius > canvas.height ) || (ball.y - ball.radius < 0) ) { ball.velocityY =- ball.velocityY; } else if ( (ball.x + ball.radius > canvas.width ) || (ball.x - ball.radius < 0)) { ball.velocityX =- ball.velocityX; } drawGame(); } }
 canvas { margin-top: 0px auto; border: 2px solid black; background-color: black; border-radius: 10px; display: block; width: 50%; }
 <,DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>Pong</title> <meta name='viewport' content='width=device-width. initial-scale=1'> <script src='main.js'></script> </head> <body> <canvas id="gameCanvas" width="800" height="600"></canvas> </body> </html>

暫無
暫無

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

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