2

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?

dfsq
  • 191,768
  • 25
  • 236
  • 258

1 Answers1

0

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.

Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Not working yet. Does the for loop still continues even if the function inside setinterval is not called? –  Feb 11 '15 at 14:39
  • The updated code still have the same problem. Can you rather see it in jsfiddle? –  Feb 11 '15 at 14:46
  • Oh, you want it to draw one pixel in 3s. Check updated code with `3000 * x` interval. – dfsq Feb 11 '15 at 14:48
  • Can you create a demo with the problem? – dfsq Feb 11 '15 at 15:11
  • I have a button on an html page. If i click the button then it will draw a line like creating a road slowly. –  Feb 11 '15 at 15:19
  • Dude what spell checker you using? undefined !== undfined – Neil Feb 11 '15 at 17:42