在 Canvas 中使用 JS 倒数计时器和 requestAnimationFrame

Use JS countdown timer in Canvas with requestAnimationFrame

本文关键字:倒数 计时器 requestAnimationFrame JS Canvas      更新时间:2023-09-26

我正在制作一个简单的画布游戏,我正在使用requestAnimationFrame(Paul Irish的版本)进行游戏循环。我在游戏中使用了 javascript 倒计时(显示秒和 100 秒),但它没有以正确的速度倒计时。我知道这与游戏的刷新率有关,因此计数器每帧更新一次,而不是每 100 秒更新一次。我该如何解决这个问题?

下面是计时器对象:

/**
 * The timer as an object
*/
function Timer(position, time) {
  this.position = position || new Vector(150,210);
  this.time = time || 6000;
}
Timer.prototype = {
  start: function() {
    console.log('start running');
    this.initial = this.time; //time in 100'ths of seconds
    this.count = this.initial;
    this.counter; //10 will  run it every 100th of a second
    clearInterval(this.counter);
    //this.counter = setInterval(this.timer, 10);
    this.timer();
  },
  timer: function() {
    //console.log(this.count);
    this.count--;
      var res = this.count / 100;
    //Show counter in canvas
    return 'Tid kvar: ' + res.toPrecision(this.count.toString().length) + ' sekunder';
  },
  draw: function(ct) {
    if(this.initial === undefined){this.start();} //Start the timer
    ct.save();
    if(this.count <=0){ //Remove timer if timer has reached 0
      ct.clearRect(this.position.x, this.position.y, Racetrack.innerTrackWidth, Racetrack.innerTrackHeight);
      return false;
    } else { //draw timer
      ct.save();
      ct.font = 'bold 3em arial';
      ct.fillStyle = 'orange';
      ct.fillText(this.timer(), this.position.x, this.position.y);
    }
    ct.restore();
  }, 
}

游戏循环和调用计时器的部分:

  var init = function(canvas) {
    timer = new Timer(new Vector(160,210), 3000);
  }
  var render = function() {
    ct.clearRect(0,0,width,height);
    ship.draw(ct);
    racetrack.draw(ct);
    //draw timer or results if timer reached 0
    timer.draw(ct) !=false ? timer.draw(ct) : endFrame.draw(ct);
  };
  var gameLoop = function() {
    var now = Date.now();
    td = (now - (lastGameTick || now)) / 1000; // Timediff since last frame / gametick
    lastGameTick = now;
    if(timer.draw(ct) == false) { //stop the game if timer has reached 0.
      cancelRequestAnimFrame(gameLoop);
      console.log('Time''s up!');
    } else { //Otherwise, keep the game going.
      requestAnimFrame(gameLoop);
    }
    update(td);
    render();
  };

我也尝试将其作为计时器对象,但是调试this.count显示第一个循环的数字,未定义的第二个循环和之后的每个循环的 NaN(我不确定这会以任何一种方式解决计时问题?

function Timer(position, time) {
  this.position = position || new Vector(150,210);
  this.time = time || 6000;
}
Timer.prototype = {
  start: function() {
    console.log('start running');
    this.initial = this.time; //time in 100'ths of seconds
    this.count = this.initial;
    this.counter; //10 will  run it every 100th of a second
    clearInterval(this.counter);
    this.counter = setInterval(this.timer, 10);
    this.timer();
  },

  timer: function() {
    console.log(this.count);
    this.count--;
  },
  getTime: function() {
    var res = this.count / 100;
    return 'Tid kvar: ' + res.toPrecision(this.count.toString().length) + ' sekunder';
  },
  draw: function(ct) {
    if(this.initial === undefined){this.start();} //Start the timer
    ct.save();
    if(this.count <=0){ //Remove timer if timer has reached 0
      ct.clearRect(this.position.x, this.position.y, Racetrack.innerTrackWidth, Racetrack.innerTrackHeight);
      return false;
    } else { //draw timer
      ct.save();
      ct.font = 'bold 3em arial';
      ct.fillStyle = 'orange';
      ct.fillText(this.getTime(), this.position.x, this.position.y);
    }
    ct.restore();
  },
}

不确定是否要求以 1/100 间隔显示时间,或者使用 setInterval 时时间是否不准确。

答:setInterval 不应用于计时,因为它远非准确,间隔越小越差,如果运行动画,情况会更糟。

B:浏览器在 1/60 秒刷新。您可以强制显示器在 1/100 秒内呈现和显示,但随后根据图形硬件,它可能永远不会显示,因为显示器当时正在扫描屏幕上其他位置的像素。或者,当您覆盖显示器时,就像图形被写入显示器

时,您会受到剪切。

使用 requestAnimationFrame 获取倒计时的最佳方式

var start = true;     // flags that you want the countdown to start
var stopIn = 3000;    // how long the timer should run
var stopTime = 0;     // used to hold the stop time
var stop = false;     // flag to indicate that stop time has been reached
var timeTillStop = 0; // holds the display time
// main update function
function update(timer){
    if(start){  // do we need to start the timer
        stopTime = timer + stopIn; // yes the set the stoptime
        start = false;             // clear the start flag
    }else{                         // waiting for stop
        if(timer >= stopTime){     // has stop time been reached?
            stop = true;           // yes the flag to stop
        }
    }
    timeTillStop = stopTime - timer;      // for display of time till stop
    // log() should be whatever you use to display the time.
    log(Math.floor(timeTillStop / 10) );  // to display in 1/100th seconds
    if(!stop){
        requestAnimationFrame(update); // continue animation until stop 
    }
}
requestAnimationFrame(update);  // start the animation

忘了添加。

通过这种方法,您永远不会获得 100 秒的精度。您将平均退出 7-8 毫秒。但除非你让它变得更复杂,否则这是你能做的最好的事情。7-8 毫秒的平均值是恒定的,并且在 2 小时 1 秒内保持不变,并且仅由大约 16 奇数毫秒的动画刷新时间决定。