I’m using canvas to draw a chart.
I would like make it “animated”, which means you can see how the lines are drawn.
So I implemented a small “sleep” function. But now it waits the sum of ms of all sleep() callings before it starts drawing anything in the canvas. How can I make it waiting between each stroke?
function sleep(ms) {
var time = new Date();
time.setTime(time.getTime() + ms);
while (new Date().getTime() < time.getTime()) {}
}
//this is how i use it, let me know if you need the whole context.
for ( var columnID in columns) {
var tempX = startX;
var tempY = startY;
this.ctx.beginPath();
this.ctx.strokeStyle = this.colors[columnID];
for ( var key in this.data) {
tempY = startY - this.data[key][columns[columnID]] * 2;
tempX = tempX + stepWidth;
this.ctx.lineTo(tempX, tempY);
this.ctx.stroke();
sleep(50);
}
this.ctx.closePath();
}
//UDATE:
setTimeout() is also beeing ignored:
jsfiddle(it messed up the scale, using fixed json, but it shows the context of my script)
You can use
setTimeOutorsetIntervalin Javascript. These functions don’t pause the execution, but sets a callback function which will be invoked after the given delay, and the syntax is as given belowe.g:
In your case it should be
and you have to pass
thisalso, so it becomesAnd in your function you are calling
setTimeoutinside a loop which will make no difference in the time between the plotting of two consecutive points in the array. Instead it plots all the points after the given delay. So you have add a delay there. This way I have fixed your version of code.see it : http://jsfiddle.net/diode/pQ4Qg/9/
But the right way to do this is to create a 2 dimensional array of points and use two functions : One to switch the path and other to draw each path.
demo here : http://jsfiddle.net/diode/pQ4Qg/11/
You can tweak this to achieve what you require.