如何将倒数计时器更改为分钟:秒

How to change the countdown timer into minutes : seconds?

本文关键字:分钟 倒数 计时器      更新时间:2023-09-26

我正在这样设计游戏,但倒数计时器仍然以秒为单位。所以我想把它改成分钟:秒。如何将其更改为分钟:秒?请给我一个解释。

//thanks to GameAlchemist
function createCountDown(timeRemaining) {
    var startTime = Date.now();
    return function() {
    return timeRemaining - ( Date.now() - startTime );
    }
}
var currentCountDown = createCountDown(30000);
// Draw everything
var render = function () {
var countDownValue = currentCountDown();
returnKillsNeeded(stageNum);
    ctx.drawImage(startGameImg, 0,0);
    ctx.font = "24px Helvetica";
    ctx.textAlign = 'center'
    ctx.textBaseline = "top";
    ctx.fillStyle="#FF0000";
    ctx.fillText("press Enter to play", 250, 450);
    ctx.fill();
    if(gameStart){
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
ctx.fillStyle="#522900";
ctx.fillRect(0,480,500,120);
ctx.drawImage(scoreImg, 22,522);
ctx.drawImage(livesImg, 360,522);
ctx.drawImage(progressImg, 200,492);
createProgressBar();
createProgressPercent();
ctx.fillText("progress", 170,492);
setEnemyHealthText();
drawPlayer();
if(countDownValue <=0){
    countDownValue = 0;
}else{
    ctx.fillText(countDownValue, 200,190);
}

1 分钟是 60 秒,对吧?

countDownValue除以 60 得到分钟,然后向下舍入 fe。 用Math.floor()使其干净。模数countDownValue 60 以获得秒。

var minutes = Math.floor(countDownValue/60);
var seconds = countDownValue%60;

然后像MM:SS一样打印时间

if(seconds > 9)
    ctx.fillText(minutes + ":" + seconds, 200,190);
else
    ctx.fillText(minutes + ":0" + seconds, 200,190);

这个 if 语句始终将时间打印为 7:06,而不是 7:6

将米利斯转换为分钟和秒

if(countDownValue <=0){
    countDownValue = 0;
}else{
    ctx.fillText(
       (countDownValue/1000/60) << 0 + 
       ':' + 
       (countDownValue/1000) % 60, 200, 190
    );
}

替换:

ctx.fillText(countDownValue, 200,190);

由:

// Convert miliseconds to seconds.
var seconds = Math.floor(countDownValue/1000);
// A minute is 60 seconds. See how many times 60 fits in the number of seconds:
var minutes = Math.floor(seconds / 60);
// Calculate how many seconds are left when removing those minutes:
seconds -= minutes * 60;
// Format the seconds to always have 2 digits
seconds = seconds.toFixed(2);
// Output the result:
ctx.fillText(minutes + ':' + seconds, 200, 190);

一些评论:

如果使用插件适合您,请不要重新发明轮子。例如:jQuery Countdown。

您提供的代码具有不平衡的大括号。当然,这应该在代码运行之前修复。