当我的秒表使用setInterval更新时,它会闪烁,如何使其平滑?

问题描述 投票:1回答:1

嗨我在javascript中制作了一个秒表,每次更新时,它都会删除,然后在第二次出现后再删除。所以它每秒出现并消失,使它眨眼。如何让它出现,直到下一次更新,平稳过渡。

这是我的代码:

function GameTimer() {
  var gameTimeMinutes = 0;
  var gameTimeSeconds = 0;
  var gameTime = "";

  this.addTime = function() {
    gameTimeSeconds += 1;
    if (gameTimeSeconds < 10) {
      gameTime = gameTimeMinutes + " : 0" + gameTimeSeconds;
    } else {
      gameTime = gameTimeMinutes + " : " + gameTimeSeconds;
    }

    if (gameTimeSeconds == 60) {
      gameTimeSeconds = 0;
      gameTimeMinutes++;
    }
  };

  this.draw = function() {
    graph.clearRect(0, 0, canvas.width, canvas.height);
    var fontSize = 25;
    graph.lineWidth = playerConfig.textBorderSize;
    graph.fillStyle = playerConfig.textColor;
    graph.strokeStyle = playerConfig.textBorder;
    graph.miterLimit = 1;
    graph.lineJoin = 'round';
    graph.textAlign = 'right';
    graph.textBaseline = 'middle';
    graph.font = 'bold ' + fontSize + 'px sans-serif';
    graph.strokeText(gameTime, 100, 30);
    graph.fillText(gameTime, 100, 30);
  };

  this.update = function() {
    this.addTime();
    this.draw();
  }.bind(this);

  this.update();
}

var playerConfig = {textBorderSize: "1px", textColor: "black", textBorder: "solid"};
var canvas = document.getElementById("timer");
var graph = canvas.getContext("2d");
var gameTimer = new GameTimer();
setInterval(gameTimer.update, 1000);
<canvas id="timer" width="200" height="100"></canvas>

所以只是为了澄清,我尝试将间隔时间改为十秒,并且它每十秒出现并消失,这意味着它在接下来的十秒内消失,直到它出现并再次消失。直到下一次更新,它才会停留在那里。

谢谢!

javascript html5 setinterval stopwatch
1个回答
0
投票

我认为闪烁可能是因为setInterval与屏幕的刷新率不同步。如果是这样,requestAnimationFrame可能能够解决这个问题。

这确实使用了不必要的系统资源,但无论如何都可以解决您的问

试试这个:

this.timeUntilUpdate = Date.now();
this.update = function(){
    if(Date.now() - this.timeUntilUpdate > 1000){
        this.addTime();
        this.draw();
    }
    requestAnimationFrame(this.update);
}

然后在最后用setInterval(gameTimer.update, 1000);替换requestAnimationFrame(GameTimer.update)或者可能只是GameTimer.update();

© www.soinside.com 2019 - 2024. All rights reserved.