I'm trying to re-create a game inspired by the minigame in New Super Mario Bros. called "Wanted!". Here's the situation:
I'm trying to have a countdown timer of 10 seconds, using JavaScript. When the timer counts down, I want the timer to refresh every second that passes. But as you'll see in the picture below, the timer writes over itself. I'm trying to do this with pure JavaScript, but HTML will also work if it is a preferred method. Keep in mind that this is a still frame. Here's what I have:
function drawTimer() {
var timeLeft = 10; // Set seconds
let countDown = setInterval(function() {
// Check if we reached 0.
if (timeLeft <= 0) {
alert("Time's up!");
isWinner = false;
document.location.reload(); // reload the page
clearInterval(countDown);
}
else { // Less than 10,
requestAnimationFrame(drawTimer);
ctx.beginPath();
ctx.font = "16px Arial";
ctx.fillStyle = "#FFFFFF";
ctx.strokeStyle = "#000000";
ctx.fillText("Time left: " timeLeft, 200, 20);
ctx.closePath();
}
timeLeft -= 1;
}, 1000);
}
CodePudding user response:
Not sure if you understand what canvas do. Its just a "canvas", as it says, and you draw pixels.
For example, if you draw something and you want to move it somewhere, you should draw new pixels on the place where that should be moved and erase previous pixels. Its like you are drawing a circle on a paper, and wanna draw it (move it) to another place (that would be another frame), you should erase current circle and draw a new one on another place.
In your case, for showing timer text you draw pixels, each drawn pixel will stay on canvas unless you erase it at some point. You should find a way to erase it, but easier would be to have an element in html that is above canvas (absolute position) and you will not have a problems with repainting.