IFD:All Hail The Pixels/ProcessingSketches: Difference between revisions

From Medien Wiki
(Added P03 example sketch)
(Added P04 and P05 example sketches)
Line 171: Line 171:
}
}


</source>
<br /><br />
=== P04 For Loop ===
<source lang="java">
/*
P04 For-Loop for repeating structures
Draw a number of rectangles in a horizontal line and dynamically
change the spacing between them according to the y-position of the
mouse.
*/
// Variable to specify the total numbers of rectangles to be drawn
int numRects = 10;
void setup(){
  size(1000,600);
  noFill();
}
void draw(){
 
  // Calculate the distance between each rectangle by
  // dividing the current mouse position by 10 (or multiply it with 0.1)
  float distance = mouseX * 0.1;
 
  // Reset the background to white
  background(255);
 
  // Move the coordinate system to the vertical center
  translate(0, height * 0.5);
 
  // Repeat the for-loop for the times of "numRects" 
  for(int i=0; i < numRects ; i++  ){
    // Draw a rectangle at the current origin of the cordinate system (0,0)
    rect(0,0,10,10);
    // Move the coordinate system to the right by the number of pixels specified in "distance"
    translate( distance ,0);
  }
}
</source>
<br /><br />
=== P05 2D Grid ===
<source lang="java">
/*
P05 2D GRID
Example to demsonstrate the usage of two nested for loops
to create a two dimensional grid pattern. The number of
rows and colums is calculated at the startup so that it
matches given space (half of the screen size) and the
specified spacing between each grid element (defined by
the variable "gridSpacing")
 
*/
// Define the spacing of the grid elements
float gridSpacing = 10;
// Inititalize variables to store the number of rows and colums
float numCols;
float numRows;
void setup(){
  size(600,600);
  // Dynamically calculate the number of colums and rows accoding to the given
  // stage size and the grid size.
  numCols = (width * 0.5) / gridSpacing;
  numRows = (height * 0.5) / gridSpacing;
}
void draw(){
  background(255);
 
  // Leave a quater of the stage blank as spacing around the
  // grid structure.
  translate(width * 0.25, height * 0.25);
   
    // Use two for loops to interate the colums and rows:
    for(float i=0; i < numCols; i+= 1 ){
      for(float j=0; j < numRows; j+= 1){
       
        // Change the appearance of dots for
        // even and odd rows
        if( j % 2 == 0){
          stroke(0);
          noFill();
        }else{
          fill(255,0,0);
          noStroke();
        }
       
        // Calculate the actual position of the individual dot:
        float x = i * gridSpacing;
        float y = j * gridSpacing;
       
        // Draw the ellipse
        ellipse(x, y, 5, 5);
     
      } 
    }
}
</source>
</source>
<br /><br />
<br /><br />