Looping in two dimensions This simple diamond pattern loops by repeating the shape in two dimensions.

How are repeating patterns like the one above created? You guessed it, they are a kind of loop!

In this case they repeat the pattern not only in one direction but in two dimensions. What does that mean?

When we create a one dimensional pattern from a row of shapes, we loop across the x access by using a counter that set the x position of the shape.
Here is the code for a one dimensional loop. Can you spot the counter which loops across the x axis? It should look familiar, if not, take a look at this tutorial.

fill(0);
for(int x=0; x<=width; x=x+radius){
}
}

To create a two dimensional pattern we loop down the y axis by using another  counter ( which draws a whole row of shapes and sets the position of the y axis. Here’s the end product:

And here’s the code. See whether you can find both the x counter and the y counter in this example:

fill(0);
for(int x=0; x<=width; x=x+radius){
for(int y =0; y<=height; y=y+radius){
}
}
}

Play around with this more complex example in a sketchpad. Can you change the diamond pattern to repeat a different shape? Can you change from two dimensions to one dimension and back? Can you change the spacing of the pattern? Be careful, the counter variables are named i and j instead of x and y.

// The message to be displayed
color white =color(255);
color yellow =color(255,255,0);
color blue =color(0,0,255);
color red =color( 95,0,0);
color green= color(0,134,0);
color darkgreen=color(0,57,0);
color purple= color(229,41,255,100);
color skyblue=color(41,250,255);
color black = color(0);
color bg = black;
int diamondSize = 20;
void setup(){
size(200,200);
smooth();
}

void draw(){
noStroke();
background(red);
setFullPattern(black, diamondSize);
//save a screenshot of the image
if (mousePressed) {
if (mouseButton == RIGHT) {
save("fabric_pattern.png");
}
}
}

void setFullPattern(color patternColor, int offset){
fill(patternColor);
for(int i=0; i<=width; i=i+offset){
for(int j =0; j<=height; j=j+offset){
beginShape(TRIANGLE_FAN);
vertex(i, j);
vertex(i, j-offset/2);
vertex(i+offset/2, j);
vertex(i, j+offset/2);
vertex(i-offset/2, j);
vertex(i, j-offset/2);
endShape();
}
}
}
1. ikamvacodes says: