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

时间:2016-04-24 15:31:21

标签: javascript

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

//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);
}

3 个答案:

答案 0 :(得分:0)

替换:

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

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

答案 1 :(得分:0)

将毫秒转换为分钟和秒

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

答案 2 :(得分:0)

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

相关问题