Javascript setInterval()函数在绘制到画布上不起作用 [英] Javascript setInterval() function not working in drawing to canvas
问题描述
我试图在画布上画一条线。我正在努力使时间线随着时间变化。我正在使用以下代码执行
I am trying to draw a line in a canvas. I am trying to make the line moving with time. I am using the following code to do so
var ctx = mycanvas.getContext('2d');
ctx.beginPath();
for (var x = 0; x < 200; x++) {
setInterval(draw(x, 0, ctx), 3000);
x = x++;
}
这是绘制函数
function draw(x, y, ctx) {
ctx.moveTo(10 + x, 400);
ctx.lineTo(11 + x, 400);
ctx.lineWidth = 10;
ctx.strokeStyle = "#ff0000";
ctx.stroke();
}
但是setInterval()函数不起作用,并且线条被立即绘制。它不等待3秒钟前进到下一个像素。
我犯错了吗?
But the setInterval() function is not working and the line is being drawn instantly. Its not waiting for 3s to proceed to next pixel. Am I making a mistake?
推荐答案
setInterval
需要一个函数作为第一个参数。现在,您只是调用 draw(x,0,ctx)
,它会返回 undefined
。因此,您的代码等效于setTimeout(undefined,3000)。
setInterval
needs a function as the first parameter. Right now you are just calling draw(x,0,ctx)
and it returns undefined
. So your code is equivalent to setTimeout(undefined, 3000).
相反,您需要提供一个可调用函数并调用 draw
从中。尝试以下操作:
Instead you need to provide a callable function and invoke draw
from it. Try this:
setInterval(function() {
draw(x, 0, ctx);
}, 3000);
另一个问题是由于循环行为中的典型闭合。您将需要创建单独的范围才能使用 x
的单个值:
Another problem is due to typical closure in loop behavior. You will need to create separate scope to be able to work with individual values of x
:
for (var x = 0; x < 200; x++) {
(function(x) {
setInterval(function() {
draw(x, 0, ctx);
}, 3000 * x);
})(x);
x = x++;
}
也请检查这个问题,以获取更多示例来解决这种情况。
Also check this question for more examples how to fix situations like this.
这篇关于Javascript setInterval()函数在绘制到画布上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!