banner



How To Create A Loop Inside A Draw Function In Js

Tutorials / p5.js Tutorials / For Loops


For Loops

tutorial p5.js javascript for-loops


  • For Loops
  • The Benefit of For Loops
  • Nested For Loops
  • Indexes
  • Summary
  • Crook Sheet
  • Homework

At present yous know how to write code using functions, variables, and if statements. And then far your code has worked by executing each line 1 later the other: if you desire to draw three circles, you'd have to write iii separate calls to the circle function.

This tutorial introduces for loops, which allow yous to repeat piece of work without repeating code.

Allow'southward start with an example sketch:

This sketch draws iii vertical lines: the showtime from position 75,0 to 55,tiptop; the second from position 150,0 to 150,elevation; and the third from position 225,0 to 225,meridian.

3 lines

Equally you read this code, effort to recognize the blueprint in the 3 lines: the x position of the first line starts at 75, and then increases past 75 for the 2d line, and stops at 225 for the third line.

When you accept a pattern like this (get-go at a number, increase past a number, stop at a number), you tin employ for loops to follow that pattern to repeat code.

For Loops

To write a for loop, first type the for keyword, and then in parentheses () provide three things:

  • Declare a variable to go on rail of your design, and initialize it to the number your pattern starts at: let lineX = 75;
  • Write a test that evaluates to a boolean value of false whenever the pattern should stop: lineX <= 225;
  • Reassign the variable so that it follows the pattern: lineX = lineX + 75; (which can be shortened to lineX += 75)

Then inside curly brackets {}, write the lawmaking that uses your variable to follow the pattern. Putting it all together, it looks like this:

This is new syntax, so let'south become over information technology slice by piece:

  • allow lineX = 75; creates a loop variable with a value of 75. This simply happens once, at the very beginning of the loop.
  • lineX <= 225; decides when to go on looping. This test is evaluated every step (which is called an iteration) of the design, at the start of the iteration. Whenever the examination evaluates to simulated, the pattern is over and the loop stops iterating.
  • lineX += 75 updates the loop variable. This happens at the end of every iteration, after the torso of the loop has run.
  • line(lineX, 0, lineX, height); uses the lineX variable to draw a line each iteration of the loop.

At the terminate of each iteration (when the code reaches the closing curly bracket }), a couple things happen:

  • The code executes your reassignment statement to update the loop variable.
  • Then the code jumps back to the beginning of the for loop.
  • The check is evaluated, and if it's truthful, the body of the loop is executed again. If it'south false, the loop exits and skips over the body.

This might seem like a lot to accept in, but you can think about information technology equally a few steps:

  1. A loop variable is created and initialized to the first number in the pattern.
  2. The check is evaluated, and if it's false, the loop exits and its body is skipped. If information technology's true, and so the body is executed.
  3. Afterward the body executes, the loop variable is updated.
  4. Then the code jumps back to the beginning of the loop and performs the bank check once again.

The Benefit of For Loops

Three lines might not seem very interesting, but for loops get in easier to make more than complicated patterns. For example, what if you wanted to draw nine lines instead of 3 lines?

You could write code that draws each line manually:

This works, but it's pretty annoying to piece of work with code like this.

Read the code and effort to notice the blueprint: the first line has an 10 value of 30, which increases past 30 each step, and ends at 270. Since you have a pattern, that means yous can use a for loop to do this in a more manageable mode:

This code uses a for loop to create a pattern where lineX starts at 30, increases by 30 each iteration, and stops when lineX is greater than 270. During each step of the pattern, the code draws a vertical line using the lineX variable.

9 lines

Here's the payoff: what if you wanted to describe 99 lines? Y'all tin can utilize a for loop to describe the blueprint for y'all instead of writing 99 lines of code:

99 lines

To understand the power of for loops, imagine writing this sketch without them!

Nested For Loops

You can put any code inside a for loop- including another for loop!

For example, let's kickoff with a programme that draws a row of circles:

This sketch uses a for loop to draw three circles: one at 75,150, some other at 150,150, and a 3rd 1 at 225,150.

three circles

You can think of this for loop as a single unit that draws a row of circles. What if y'all wanted to describe three rows of circles?

You could use three separate for loops, i for each row:

three rows of circles

This lawmaking works, but it's going to be annoying if yous want to add some other circle to each row, or change the bore of the circles: y'all'd have to change the code in three different places.

Looking at the vertical position of each row, you might notice a pattern: it starts at 75, increases by 75 each step, and ends at 225. This sounds like a job for another for loop!

The outer loop creates a circleY variable and iterates three times. During each iteration of the outer loop, the inner loop creates a circleX variable and iterates three times. The cease result is nine circles in a filigree, or three rows of three circles each.

Effort thinking well-nigh the inner for loop as a single unit, and the outer for loop equally a loop that executes that unit multiple times. To make that explicit, y'all could put the inner for loop within a function, which gets chosen from the outer loop:

This lawmaking does the same thing equally before, but information technology encapsulates the inner for loop inside the drawCircleRow role. The for loop inside the draw function calls the drawCircleRow function 3 times. The drawCircleRow function uses its ain for loop to depict a row of circles.

Moving your inner for loop into a function tin help yous think of information technology as a unmarried unit, and tin make your code easier to read.

Indexes

The above examples used loop variables that were then used directly in the body of the for loop, like lineX and circleX.

Another common approach you'll see is to employ index loop variables (often named i or j) that represent how many times the loop should iterate.

Here's the line case from above, using an alphabetize loop variable:

9 lines

This lawmaking nonetheless does the aforementioned thing, but information technology'south more obvious how many lines will exist drawn by reading the for loop. The pattern is created by basing the lineX variable off the i variable, and increasing the i variable by i each iteration of the loop.

This approach also makes it easier to utilise multiple effects to your pattern. For example, this code increases the thickness of the lines as they get closer to the right side of the window:

thicker lines

Whether y'all use an alphabetize variable or not is up to you and what seems easier to read. You'll meet both approaches in other people's lawmaking.

Summary

A for loop lets you repeat a pattern without writing the same line of code over and over once more. You should employ a for loop when you have code that uses a pattern that starts at a number, increases past a number, and stops at a number.

A for loop inside of some other for loop is chosen a nested for loop. These are useful when your blueprint involves more than one number or if y'all're working with grids.

You lot tin utilise an alphabetize variable to base of operations your for loop on which step of the pattern you're on, which makes it easier to utilize multiple furnishings at in one case.

Cheat Sheet

cheat sheet

Homework

  • Write a programme that gives you the total of one+2+3+4+…+100. Hint: endeavor it without for loops offset and endeavor to find a design.
  • Draw a 10x10 grid that fills upwards the window, no matter what size the window is.
  • Write a plan that draws a horizontal slope. Hint: starting time with grayscale.
  • Write a program that makes every pixel in the window a different random color.
  • Write a programme that draws a flower with 8 petals. Hint: try it without for loops first and try to find a pattern.

Comments and Questions

Happy Coding is a community of folks just like you learning about coding.
Practise you have a comment or question? Post it hither!


Source: https://happycoding.io/tutorials/p5js/for-loops

Posted by: solomonstrel1937.blogspot.com

0 Response to "How To Create A Loop Inside A Draw Function In Js"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel