WEEK: 8
Active: February 28th - March 6th
Work Due: March 7th @ 9:00AM

For Loops and Drawing

A very common use of for loops is to do something from one place on a screen, to another place on a screen. For example, you may find yourself wanting to do something, or rather the same things, from the left area of a canvas (x=0), to the right edge of a canvas (x=width).

In this situation, you will likely setup your for loop such that;

  1. the variable declaration’s name is meaningful to the task at hand. If you are working across the x-axis, x may be the most suitable.
  2. You will want to initialize this value to the left-edge of the area where you want something to occur.
  3. The conditional check statement should cause the loop to terminate once it reaches the right-edge of the desired area. Again, if you were working from left-edge to right-edge of a canvas in p5, this likely would be some sort of conditional, checking whether the variable is at or past the canvas’ width ( x < width ).
  4. Finally, for the update statement, this should cause the variable’s update to reflect the movement across the screen that you are trying to accomplish. Let’s say you wanted to draw circles across the screen’s x-axis, starting at x=0 and terminating at x=width. You would obviously set up the for loop so that it started at 0 and ended at width. The update statement will be dependent on the desired size and spacing of the circles. For example, if we want circles with a width of 50px, that touch, then our update value will likely need to be x+=50.

This example is shown in one possible solution below, with the description for the circles applied to both the x-axis and y-axis.

[ Code Download ] [ View on GitHub ] [ Live Example ]

Drawing A Diagonal Series

What if you wanted to draw a diagonal series on a canvas that what not square? The problem is obviously that we cannot use the same variable to describe the position of an object for both the x-axis and y-axis.

The following example utilizes the properties we have been talking about, applied to the problem of drawing a diagonal line of objects across a screen of indeterminate length.

[ Code Download ] [ View on GitHub ] [ Live Example ]

Previous section:
Next section: