这是重要的代码部分:
function drawCircle(i, color1, color2) {
var ctx = canvas.getContext("2d");
if (i % 2 == 1) {
ctx.fillStyle = color1;
}
else {
ctx.fillStyle = color2;
}
ctx.beginPath();
ctx.arc(110, 270, 10, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
for (var i = 0; i < 10; i++) {
setTimeout(drawCircle(i, color2, color5), 4000);
}
请注意,这只是我想在更大的项目中使用与此类似的代码之前尝试的一个片段。这不能正常工作,图像只绘制一次,也就是说,我只看到绘制的最后一个圆圈。我已经用谷歌搜索死了,但到目前为止没有任何帮助。
最佳答案
您要使用的是setInterval
。 setTimeout
只触发事件一次。它们具有相同的参数列表。
此外,我认为您使用 setTimeout
的方式不正确。按照您现在的编写方式,该函数在实际将任何内容传递给 setTimeout
/setInterval
之前被触发。所以你应该写:
setInterval(function() { // GOOD. An actual function is passed
drawCircle(...); // as the first argument.
}, 4000);
或:
setInterval('drawCircle(...)', 4000); // GOOD. the JS statement is supplied as
// a string and later on will be evaluated
// and executed with eval().
和不:
setInterval(drawCircle(...), 4000); // BAD! drawCircle() is fired, its result
// evaluated and passed on to setInterval
// that doesn't know what to do with it.
编辑
您在 JavaScript 中没有任何阻塞例程。它是一种单线程、事件驱动的语言。如果您调用类似 setInterval
的方法,它会立即成功。只有在 4 秒左右后,您的回调函数才会被调用。然而与此同时,JS 将忙于做各种不同的事情——例如对用户生成的其他事件使用react。您要做的是调用 setTimeout
一次,然后在回调函数内部调用,就在返回之前使用相同的函数和 i
的一组不同参数再次调用它。沿着这些线的东西:
function drawCircle(i, ...) {
// ... do stuff ...
if (i < 10) { // Check if the callback has been invoked 10
// times already.
setTimeout(function() { // Schedule the callback for execution
drawCircle(i + 1, ...); // again after anoter 4 seconds.
}, 4000);
}
}
setTimeout(function() { // Invoke the callback the first time
drawCircle(1, ...); // after first 4 seconds.
}, 4000);
关于javascript - 我想以一定的间隔在 Canvas 上绘制,但 setTimeout 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850231/