【发布时间】: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);
<canvas id="timer" width="200" height="100"></canvas>
所以为了澄清一下,我尝试将间隔时间更改为 10 秒,每隔 10 秒它就会出现和消失,这意味着它会在接下来的 10 秒内消失,直到它再次出现和消失。在下次更新之前它不会一直存在。
谢谢!
【问题讨论】:
-
我在该代码中没有看到对
beginPath()的任何调用。 -
你在你的对象 GameTimer 中调用更新。我将删除这一行 // this.update()
-
不,它还在闪烁 Marouen,还有其他想法吗?
-
并添加 beginPath() 也不会改变任何内容。
-
在 Chrome 中运行 sn-p 看起来不错。你使用的是什么浏览器?另外,您为什么要在
canvas而不是普通的 HTML 元素中这样做?文本使用 HTML 会更好看。
标签: javascript html setinterval stopwatch