【问题标题】:When my stopwatch updates with setInterval, it blinks, how to make it smooth?当我的秒表使用 setInterval 更新时,它会闪烁,如何使其平滑?
【发布时间】:2018-06-11 15:36:48
【问题描述】:

您好,我用 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);
&lt;canvas id="timer" width="200" height="100"&gt;&lt;/canvas&gt;

所以为了澄清一下,我尝试将间隔时间更改为 10 秒,每隔 10 秒它就会出现和消失,这意味着它会在接下来的 10 秒内消失,直到它再次出现和消失。在下次更新之前它不会一直存在。

谢谢!

【问题讨论】:

  • 我在该代码中没有看到对 beginPath() 的任何调用。
  • 你在你的对象 GameTimer 中调用更新。我将删除这一行 // this.update()
  • 不,它还在闪烁 Marouen,还有其他想法吗?
  • 并添加 beginPath() 也不会改变任何内容。
  • 在 Chrome 中运行 sn-p 看起来不错。你使用的是什么浏览器?另外,您为什么要在 canvas 而不是普通的 HTML 元素中这样做?文本使用 HTML 会更好看。

标签: javascript html setinterval stopwatch


【解决方案1】:

我认为闪烁可能是 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多