Vlad Otrocol
Vlad Otrocol

Reputation: 3172

Canvas draw shapes on the go

When I run it the browser loads for a while and then displays the whole canvas. How can I make it display as soon as it finishes one loop iteration?And why is this code not doing what I expect it to?

This is my code:

  for(var i=0;i<50;i++){
    for(var j=0;j<50;j++){
        ctx.beginPath();
        ctx.fillRect(10*j, 10*i, 10, 10);
        ctx.fillStyle = 'rgb('+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+')';
        ctx.fill();
        ctx.closePath();
        sleep(10);
    }
  }


function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
      }
   }
 }

OK... I managed to achieve the desired effect using

window.requestAnimationFrame(draw);

However can someone please explain why the code above behaves the way it does? Why does it draw all 2500 shapes before it displays the canvas?

Upvotes: 0

Views: 160

Answers (1)

markE
markE

Reputation: 105015

Use requestAnimationFrame

Here's code and a Fiddle: http://jsfiddle.net/m1erickson/NRBy5/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var RAF;
    var i=0;
    var j=0;

    function animate() {

      // draw stuff
      ctx.beginPath();
      ctx.fillRect(10*j, 10*i, 10, 10);
      ctx.fillStyle = 'rgb('+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+')';
      ctx.fill();
      ctx.closePath();


      // update
      j+=1;
      console.log(i+"/"+j);
      if(j>=50){
          i+=1;
          j=0;
          if(i>=50){
              cancelAnimationFrame(RAF);
          }
      }

      // request new frame
      RAF=requestAnimationFrame(function() { animate(); });

    }
    animate();


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Upvotes: 1

Related Questions