You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Canvas游戏计时器结束时弹出提示框?

解决Canvas小游戏倒计时结束弹窗问题
  • 核心逻辑:在倒计时更新的环节里,每次检查剩余时间是否归0,一旦时间到点,立刻终止计时逻辑,弹出提示框,同时暂停游戏的主循环。

  • 若你用setInterval实现倒计时,可这样修改代码:

    // 初始化倒计时总秒数,比如60秒
    let timeLeft = 60;
    // 存储定时器ID,用于后续清除
    let timerTimer;
    
    function startCountdown() {
      timerTimer = setInterval(() => {
        timeLeft--;
        // 格式化时间为分:秒显示
        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        document.getElementById('timer').textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
    
        // 时间到0时触发结束逻辑
        if (timeLeft <= 0) {
          clearInterval(timerTimer); // 关闭定时器,避免重复触发
          alert('Game Over, you ran out of time');
          // 可选:禁用答题交互,比如按钮置灰
          document.getElementById('answerBtn').disabled = true;
        }
      }, 1000);
    }
    
  • 若你用requestAnimationFrame做游戏主循环(更适配Canvas游戏),可这样调整:

    const totalGameTime = 60 * 1000; // 总时长60秒,单位毫秒
    let gameStartTimestamp = Date.now();
    let gameLoopId;
    
    function gameLoop() {
      const elapsedTime = Date.now() - gameStartTimestamp;
      const remainingTime = totalGameTime - elapsedTime;
    
      // 时间耗尽时触发结束
      if (remainingTime <= 0) {
        cancelAnimationFrame(gameLoopId);
        alert('Game Over, you ran out of time');
        return; // 终止循环,不再执行后续游戏逻辑
      }
    
      // 格式化剩余时间并更新显示
      const minutes = Math.floor(remainingTime / (1000 * 60));
      const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
      document.getElementById('timer').textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
    
      // 你的游戏核心逻辑:绘制红球、处理答题判断等
      drawRedBall();
      checkAnswer();
    
      gameLoopId = requestAnimationFrame(gameLoop);
    }
    
    // 启动游戏和倒计时
    gameLoopId = requestAnimationFrame(gameLoop);
    
  • 关键注意事项:

    • 必须清除定时器或取消动画帧,防止时间到点后游戏逻辑仍在后台运行
    • 时间结束后建议禁用答题交互元素,避免玩家继续操作

内容的提问来源于stack exchange,提问作者user3569752

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:55:19