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;
x
may be the most suitable.width
( x < width
).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 ] |
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 ] |