Javascript setInterval() function not working in drawing to canvas

喜夏-厌秋 提交于 2020-08-25 07:26:46

问题


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++;
}

And here is the draw function

function draw(x, y, ctx) {
    ctx.moveTo(10 + x, 400);
    ctx.lineTo(11 + x, 400);
    ctx.lineWidth = 10;
    ctx.strokeStyle = "#ff0000";
    ctx.stroke();
}

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?


回答1:


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).

Instead you need to provide a callable function and invoke draw from it. Try this:

setInterval(function() {
    draw(x, 0, ctx);
}, 3000);

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.



来源:https://stackoverflow.com/questions/28456898/javascript-setinterval-function-not-working-in-drawing-to-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!