Skip to content

Instantly share code, notes, and snippets.

@bmoren
Last active February 3, 2018 21:50
Show Gist options
  • Save bmoren/ceeb8f15a6930a862778e97d7e646daf to your computer and use it in GitHub Desktop.
Save bmoren/ceeb8f15a6930a862778e97d7e646daf to your computer and use it in GitHub Desktop.
10 print in p5js using nested loops
let gridSize = 15; //set the size of the grid
//we're doing everything inside of the setup so that we can clearly see the results, what happens in the draw loop?
function setup() {
createCanvas(windowWidth,windowHeight); // create a new canvas that fills the screen.
background(0,0,255)// set the background to blue
stroke(255) // set the stroke color to white
strokeWeight(4) //set the stroke to 4px weight
//nested for loop, remmeber, in this case it will move over one X column, then draw down all of the y's, move over one x col, draw all of the y's, etc.
for (let x = 0; x <= width; x+= gridSize) { //start at 0,increase the x by the gridSize, check to see if we hit the right edge, the width.
for (let y = 0; y <= height; y+= gridSize) { // every time we move over for the x, lets draw the y's down. start at 0, increase by the gridSize, check to see if we're at the bottom, the height.
if(random(1) < 0.5){ //flip a coin (50/50 chance for 1 to be less than 0.5)
line(x,gridSize+y,gridSize+x,y) // draw a line one way
}else{
line(x,y,gridSize+x,gridSize+y) //draw a line the other way
}
} //end y for loop
} //end x forloop
} //end setup()
function draw() {
//you could also use the noLoop() function here to stop the draw from looping and and put the code above here for the same effect!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment