I am trying to make a light weight progress bar using canvas. The target for this project is to have a progress bar filled to N percent from a given variable. For the purpose of this demo, I have manually set a 50% fill.
There are two colors: red which is filled by when loaded and green represents the progress completed.
How can I animate the progression of the green fill?
var canvas = document.getElementById('myProgress');
var myPerc = 500;
ctx = canvas.getContext('2d');
ctx.fillStyle = "rgb(255, 0, 0)"; //red
ctx.fillRect(0,0,myPerc,100);
ctx.save();
for (var i=0;i<(myPerc*0.5);i++)
{
ctx.fillStyle = "rgb(0, 255, 0)"; //green
setTimeout(function() {
ctx.fillRect(0,0,+i,100);
}, 1000);
}
There are 2 issues with the code as posted. First, you are setting the duration of each timeout to 1000. This means that each timeout will finish in one second, all at the same time. I’m assuming instead that you want them to be one second apart.
The 2nd is a very common issue with using
iin a loop insetTimeout. You can find answers to that all over SO. This seems to be one of the more thorough: JavaScript closure inside loops – simple practical exampleWith both of those issues fixed, you get this:
http://jsfiddle.net/ZpRm7/1/
You might consider
setIntervalor some other approach to avoid creating so many timeouts at once.