Course notes 16
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses
Javascript Loops and Canvas

Basic Types of loops

  • For
  • While
For Loops - will repeat a set number of times

For Loops

   for ( initialize variable; condition; increment variable  ) {
        run this code  
    }           
 <script type="text/javascript">
for (var i=0;i<=5;i++) {
//do something here }
</script>

For Loops, compress a loop's control flow structure into the declaration parameters. Writing a For Loop is broken down into three parameters, separated by a semi-colon, which together describe the entire loop's functionality. The first parameter initializes a variable for use in the loop's evaluation. The second parameter is the actual condition which the loop checks against, and the final parameter augments the loop's variable. Unlike While Loops, For Loops are better utilized in situations where an exact number of iterations are known, as the loop is more encapsulated; isolating its evaluation.

In the example, a For Loop is used to place exactly 4 rectangles into the canvas. Notice that the loop's variable is initialized to 0, and thus the conditional checks against a "<", as opposed to a "<=". Also, where a position variable was used in the While Loop to track the placement of rectangles, here the loop's variable, which is incremented every run, is used to offset the rectangles.

    function init(){
        var canvas = document.getElementById('mycanvas');
        var ctx = canvas.getContext('2d');
        var width = canvas.width;
        var height = canvas.height;
        
        var rectSize = 40;
        for(var i=0;i<4;i++) {
            ctx.fillRect((rectSize+10)*i,height/2,rectSize,rectSize);  
        }
    }

Another example of how to use canvas and a For Loop:
 <script>
    function init() { 
       var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d'); ctx.beginPath(); for (var i=0;i<=5;i++) { ctx.arc(220, 100, 20*i, Math.PI * 2, false); } ctx.closePath(); ctx.stroke(); } </script>

See results of the For Loop

While Loops - will repeat until a condition is met
    while( condition=true ) {
        run this code 
    }

While Loops, or "Conditional Loops," allow you to execute a set of commands until the expressed condition is met. They are most useful in situations where the number of iterations is unknown, or when making Boolean comparisons. To avoid infinite loops, it is important to double check that the value being checked against the condition is in some way changed within the loop.

In the example, a While Loop is used to place subsequent rectangles across the surface until the position reaches the edge.

    function init(){
        var canvas = document.getElementById('mycanvas');
        var ctx = canvas.getContext('2d');
        var width = canvas.width;
        var height = canvas.height;
        
        var rectSize = 40;
        var position = 0;
        while(position < width) {
            ctx.fillRect(position,height/2,rectSize,rectSize); 
            position += rectSize + 10; 
        }
    }

Step 1: Initialize the loop variable
Step 2: Go through the loop if the loop variable condition is not met
Step 3: Do something
Step 4: Increment the loop variable

Another way of setting up the While Loop: initialize the variable before you get in and increment it once you are in the loop.

***Make SURE you change the variable inside the loop or you will never be able to get out of the loop.
The i++ increments the variable that is being checked each time through the loop.

 <script type="text/javascript">
    var i=0;
    while (i<=5) {
       //do something here
       i++;
    }
 </script>

Another example of how to use the While Loop:

 <script>
function init() {
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "rgb(0,0,255)";
var i=0;
while (i<=30) {
ctx.moveTo (i*10, i/10);
ctx.lineTo(0,150);
i++;
}
ctx.stroke();
}
</script>

See results of the While Loop

Nested Loops

By placing loops within loops, the execution of a code block can take on multiple dimensions. For each run of the outside loop, the inside loop will complete all of its runs. This allows for more complex algorithms to be constructed, taking advantage of multiple layers of repetition.

Building off the previous example, by placing the For Loop within another loop, multiple rows are drawn by deriving the y position based on the iteration of the outer loop.

    function draw_ex03(){
        var canvas = document.getElementById('ex03');
        var ctx = canvas.getContext('2d');
        var width = canvas.width;
        var height = canvas.height;
        
        var rectSize = 40;
        for(var i=0; i<3; i++){
            var yPos = (rectSize+10)*i;
            
            for(var j=0;j<4;j++) {
                ctx.fillRect((rectSize+10)*j,yPos,rectSize,rectSize);  
            }
        }
    }
            

This example creates a star burst:
 <script>
   function init() { 
      var canvas = document.getElementById('mycanvas');
      var ctx = canvas.getContext('2d');
      ctx.beginPath();
		ctx.strokeStyle = "rgb(0,0,255)";
      ctx.lineWidth = 1; 
      for (var i=0;i<=5;i++)  {     
          var j=0;
          while (j<=6) { 
             theX=(j*35)+10;
             theY=(i*35)+10;
             ctx.moveTo(theX,theY);
             ctx.lineTo(0,0);
             j++;
          }
      }
      ctx.stroke();
   }
 </script>
                      

See results of the Grid of Boxes


In a slightly more complex example, we can create a blending color palette by deriving the color values and location entirely from the position within the looping structures.

    function draw_ex04(){
        var canvas = document.getElementById('ex04');
        var ctx = canvas.getContext('2d');
        var width = canvas.width;
        var height = canvas.height;
        
        var rectSize = width/height;
        for(var i=0; i<(width/rectSize); i++){
            for(var j=0;j<(height/rectSize);j++) {
                ctx.fillStyle = 'rgb('
                +Math.floor(255-rectSize*i)
                +','
                +Math.floor(255-rectSize*j)
                +',0)';
                ctx.fillRect(rectSize*i,rectSize*j,rectSize,rectSize);  
            }
        }
    }
            
Calling Functions

<script> function doDots(theCanvas, theY, cols) {
for (var i=0;i<=cols;i++) {
theCanvas.strokeRect((i*50)+13,theY,25,25);
}
}
function doOuterPart(theCanvas) {
theCanvas.fillStyle = "rgb(150,0,255)";
theCanvas.fillRect(0,0,400,400);
theCanvas.clearRect(100, 150,300,100); }
function doInnerPart(theCanvas, size, theStrokeColor) {
theCanvas.fillStyle = theStrokeColor;
theCanvas.lineWidth = size;
theCanvas.beginPath();
theCanvas.arc(335, 200, 150, Math.PI*2, false);
theCanvas.arc(380, 200, 75, Math.PI*2, false);
theCanvas.stroke();
}
function drawBoxes(theCanvas, theColor) {
theCanvas.strokeStyle = theColor;
doDots(theCanvas, 65, 7);
doDots(theCanvas, 190, 1);
doDots(theCanvas, 310, 7);
}

function init() {
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
doOuterPart(ctx);
doInnerPart(ctx, 5, "rgb(160,160,10)");
drawBoxes(ctx, "yellow");
} </script>

See results of the example of calling functions