I habe been watching the canvas tutorial on YouTube. They've been excellent.
I have used the explantion of expisode 1 to 3 to create a table tennis game. Now, I'm at the end of the game and I don't know who to stop the annimation. I'd like to stop the code, as soon as on player reach 21 points. The score of each player is stored in a variable. This is the animation function and its execution.
function annimation() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
tableStyle();
requestAnimationFrame(annimation);
ball.update();
racketLeft.draw();
racketRight.draw();
}
annimation();
Where do I have to put the if statement to stop execution?
I've posted this question below the following youTube video: https://www.youtube.com/watch?v=yq2au9EfeRQ
Thank you for your support.
Try something like this:
let animationId
function annimation() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
tableStyle();
animationId = requestAnimationFrame(annimation);
ball.update();
racketLeft.draw();
racketRight.draw();
if (score === 21) cancelAnimationFrame(animationId)
}
annimation();
This'll stop your animation whenever score is equal to 21
, just make sure you have score
declared somewhere.
Want to participate?
Create a free Chris Courses account to begin