Canvas How to - Create progressbar like animation








Question

We would like to know how to create progressbar like animation.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--  w  w w.j  a va  2  s .  co m-->
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var i = 0;
    var j = 0;
    var pixelCount = canvas.width * canvas.height;
    draw();
    function draw() {
        ctx.beginPath();
        var iterations = 0;
        while (iterations++ < 1000) {
            ctx.rect(j, i, 1, 1);
            if (++j > canvas.width - 1) {
                i++;
                j = 0;
            }
            if (i * j > pixelCount) {
                break;
            }
        }
        ctx.fill();
        if (i * j <= pixelCount) {
            setTimeout(function () {
                draw();
            }, 1000);
        }
    }
}
</script>
</head>
<body>
  <canvas width="100" height="100" id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: