(6 intermediate revisions by the same user not shown) | |||
Line 294: | Line 294: | ||
<source | <source lang="java"> | ||
/* | /* | ||
Line 338: | Line 338: | ||
</source> | </source> | ||
<br /><br /> | <br /><br /> | ||
=== P07 Array Layout === | === P07 Array Layout === | ||
<source | <source lang="java"> | ||
/* | /* | ||
Line 403: | Line 401: | ||
<br /><br /> | <br /><br /> | ||
=== P08 Grid By Image === | |||
Make sure you have the [[Media:layout_pixels_example.png]] file in the data folder of the sketch! | |||
<source | <source lang="java"> | ||
Line 418: | Line 417: | ||
are used to modify the grid layout. | are used to modify the grid layout. | ||
NOTICE: Make sure the image " | NOTICE: Make sure the image "layout_pixels_example.png" is placed in the "data" folder of | ||
this sketch! | this sketch! | ||
Line 437: | Line 436: | ||
// Load the actual image file from the data folder and | // Load the actual image file from the data folder and | ||
// assign it to the img variable | // assign it to the img variable | ||
img = loadImage(" | img = loadImage("layout_pixels_example.png"); | ||
// How many pixels did we load? | // How many pixels did we load? | ||
Line 468: | Line 467: | ||
} | } | ||
} | } | ||
} | |||
</source> | |||
<br /><br /> | |||
== 28.11.2014 Processing sketches == | |||
=== P09 Interval timer === | |||
Make sure you have the files [[Media:interval_pixels_example_A.png]], [[Media:interval_pixels_example_B.png]] and [[Media:interval_pixels_example_C.png]] in the data folder of the sketch! | |||
<source lang="java"> | |||
/* | |||
P09 Interval timer | |||
A refinement of the "Grid by image" example with multiple changing | |||
images. The millis() function is utilized to create an interval | |||
timer which changes the actual image from the image sequence stored | |||
in an array. The mouse x position changes the size of the grid dynamically. | |||
Therefor the map() function is used to scale the range of the screen | |||
width to the desired range for controlling the grid size. | |||
*/ | |||
float gridSize = 10; | |||
// Array of images (of type PImage) with the size | |||
// of 3 is initializied | |||
PImage[] images = new PImage[3]; | |||
// Counter for the current index of the image sequence | |||
int imageCounter = 0; | |||
// Variable to define the timer interval in milliseconds | |||
int timerInterval = 400; | |||
// Helper variable to store the last time the interval time has passed | |||
int lastMillis = 0; | |||
void setup() { | |||
size(1000, 600); | |||
// Assign individual images from the data folder | |||
// to the array positions | |||
images[0] = loadImage("interval_pixels_example_A.png"); | |||
images[1] = loadImage("interval_pixels_example_B.png"); | |||
images[2] = loadImage("interval_pixels_example_C.png"); | |||
} | |||
void draw() { | |||
background(0); | |||
// The millis() function returns the number of milliseconds | |||
// (thousandths of a second) since starting the program. | |||
// When lastMillis is substracted from millis(), we get the | |||
// milliseconds which have been past since the last timer execution. | |||
if( millis() - lastMillis > timerInterval ){ | |||
// Now count up the imageCounter by 1 | |||
imageCounter++; | |||
// Make sure it stays within the bounds of the images array | |||
imageCounter = imageCounter % images.length; | |||
// It is important to set lastMillis to the actual number | |||
// of milliseconds, otherwise the if condition does not | |||
// work repetitively. | |||
lastMillis = millis(); | |||
} | |||
// Helper variable to store the actual image from the array. | |||
PImage currentImg = images[imageCounter]; | |||
// Only show the background image when a keyboard key is pressed | |||
if(keyPressed){ | |||
image(currentImg, 0, 0); | |||
} | |||
// Dynamically scale the gridSize according to the mouse | |||
// x position | |||
gridSize = map(mouseX, 0, width, 5, 30); | |||
// Loop through the columns and rows of the grid | |||
// as in the previous example | |||
for (int x=0; x < width; x+= gridSize) { | |||
for (int y=0; y < height; y+= gridSize) { | |||
color c = currentImg.get(x, y); | |||
if (brightness(c) < 255 ) { | |||
ellipse(x, y, 5, 5); | |||
} | |||
} | |||
} | |||
} | |||
</source> | |||
<br /><br /> | |||
=== P10 Linear movement and direction === | |||
<source lang="java"> | |||
/* | |||
P10 Linear movement and direction | |||
The famous "bouncing ball"illustrates how steady movement | |||
is achived by adding a constant number (speed) to the actual | |||
position of an ellipse. The horizontal or vertical direction | |||
is changed when the ellipse hits an edge of the sketch window. | |||
*/ | |||
float rad = 60.0; | |||
float xpos, ypos; | |||
float xspeed = 2.8; | |||
float yspeed = 2.2; | |||
int xdirection = 1; | |||
int ydirection = 1; | |||
void setup() | |||
{ | |||
size(640, 360); | |||
noStroke(); | |||
frameRate(30); | |||
ellipseMode(RADIUS); | |||
xpos = width/2; | |||
ypos = height/2; | |||
} | |||
void draw() | |||
{ | |||
background(102); | |||
xpos = xpos + ( xspeed * xdirection ); | |||
ypos = ypos + ( yspeed * ydirection ); | |||
if (xpos > width-rad || xpos < rad) { | |||
xdirection *= -1; | |||
} | |||
if (ypos > height-rad || ypos < rad) { | |||
ydirection *= -1; | |||
} | |||
ellipse(xpos, ypos, rad, rad); | |||
} | |||
</source> | |||
<br /><br /> | |||
=== P11 Polar dots === | |||
<source lang="java"> | |||
/* | |||
P11 Polar dots | |||
Illustrates how circular shapes and movements are created by using | |||
polar coordinates (angle and radius) and how to convert these to cartesian | |||
coordinates (x and y) by using sine and cosine functions (sin() and cos()). | |||
*/ | |||
// Radius | |||
float r; | |||
// Radius offset | |||
float rOffset = 1.0; | |||
// Angle and speed | |||
float angle = 0.0; | |||
float angleSpeed = 0.02; | |||
void setup() { | |||
size(1000, 600); | |||
ellipseMode(CENTER); | |||
// Set r according to the sketch height | |||
r = height * 0.25; | |||
background(255); | |||
} | |||
void draw() { | |||
// Dynamically scale the radius with the mouse x position | |||
rOffset = map(mouseX, 0, width, 0.0, 1.5); | |||
// Draw a semi-transparent rectangle across the whole window | |||
// to let the backround smoothly fade out. | |||
fill(255,10); | |||
rect(0,0,width,height); | |||
// Move to the center | |||
translate(width/2, height/2); | |||
// Convert polar to cartesian coordinates | |||
// and scale the actual radius | |||
float x = (r * rOffset) * cos(angle); | |||
float y = (r * rOffset) * sin(angle); | |||
// Draw the moving red ellipse to the actual position | |||
noStroke(); | |||
fill(200,0,0); | |||
ellipse(x, y, 17, 17); | |||
// Draw the steady circle | |||
stroke(0,10); | |||
noFill(); | |||
ellipse(0,0,r*2,r*2); | |||
// Increase the current value of angle by the value of angleSpeed | |||
angle += angleSpeed; | |||
} | } | ||
</source> | </source> | ||
<br /><br /> | <br /><br /> |
Latest revision as of 09:22, 2 December 2014
17.10.2014 Processing sketches
P01 Shapes and Relations
/*
P01 Shapes and Relations
This example illustrates how to formulate properties in relation to each other.
Also the following principles are introduced:
- Usage of the setup() and draw() functions
- Drawing of basic shapes and colors
- Definition and usage of variables > dimension, halfDimension and border
- Dynamic mouse input to influence the state of the programm during runtime
- Output values to the console with print() and println()
*/
void setup() {
// set the canvas size
size(1000, 600);
}
void draw() {
// set background color to white
background(255);
// no fill color
noFill();
// variable for the size of the rectangle and the ellipse
float dimension = mouseX;
// variable for the distance between the red lines and the center shapes
float border = mouseY * 0.2;
// set the stroke color to black
stroke(0);
// use the center as origin when drawing rectangles
rectMode(CENTER);
// draw a rectangle on the left side of the canvas with varaible dimensions
rect(250, 300, dimension, dimension);
// draw a circle on the right side of the canvas with varaible dimensions
ellipse(750, 300, dimension, dimension);
// calculate and store half of the current dimension (for better readability)
float halfDimension = dimension * 0.5;
stroke(255, 0, 0);
// draw the two lines according to the dimension of the shapes and the vertical border
line(250 - halfDimension, 300 - halfDimension - border, 750 + halfDimension, 300 - halfDimension - border);
line(250 - halfDimension, 300 + halfDimension + border, 750 + halfDimension, 300 + halfDimension + border);
// output the actual dimension and border values to the console
print("dimension:");
println(dimension);
print("border:");
println(border);
}
P02 Custom Functions
/*
P02 Custom functions and transformations
This example shows how to write custom functions and how to use the
transform() and the rotate() statements to move and rotate the canvas.
It also illustrates the possibility to store and restore a certain
transformation state with pushMatrix() and popMatrix().
*/
void setup(){
size(1000,600);
background(0);
// move to the center of the canvas
translate(width * 0.5, height * 0.5);
// draw an arrow and a cross with the size of 10 pixels
arrow();
crossShape(10);
// store the actual position (in this case the center of the stage)
pushMatrix();
// move 200 pixels to the right from the canvas center
translate(200, 0);
// rotate the canvas by 60 degrees
rotate( radians(60) );
// draw an arrow and a cross to this new rotated location
arrow();
crossShape(10);
// recall the previously stored position (the center of the
// canvas which was done using the pushMatrix() statement)
popMatrix();
// move 100 pixels down from the center of the canvas
translate(0,100);
arrow();
crossShape(10);
}
// Define a new function which draws a red arrow to the actual origin of the canvas
void arrow(){
stroke(255,0,0);
line(0,0,50,0);
line(45,-5,50,0);
line(45,5,50,0);
}
// Define a new function which draws a black cross depending on the passed parameter "dimension"
void crossShape(float dimension){
float halfDimension = dimension * 0.5;
stroke(255);
line(-halfDimension, -halfDimension, halfDimension, halfDimension );
line( halfDimension, -halfDimension, -halfDimension, halfDimension);
}
07.11.2014 Processing sketches
P03 Nested Rects
/*
P03 Nested Rectangles with a while loop
Demonstration of how to make a repetetive structure using
a while-loop. Here the variable "rectSize" is decreased in
every step and the coordinate system is rotated a little bit
as well. The while-loop is executed as long as the value
of rectSize is larger than zero (rectSize > 0).
*/
size(1000,600);
// variable with the start size of the rectangles structure
int rectSize = 500;
// variable to specify the amount the rectangles are shrinked in each step
int difference = 30;
background(255);
// since all shapes are aligned centered, the center rect mode is used
rectMode(CENTER);
noFill();
// set the origin of the coordinate system to the center of the stage
translate(width/2, height/2);
// continue the following statements within the while-loop as long as the value
// of the variable "rectSize" is larger than 0
while(rectSize > 0){
//draw a rectangle with the actual size of "rectSize"
rect(0,0,rectSize,rectSize);
// for the next loop: decrease the value of "rectSize" by the value of "difference"
rectSize = rectSize - difference;
// rotate the coordinate system by 4 degrees
rotate(radians(4));
}
P04 For Loop
/*
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);
}
}
P05 2D Grid
/*
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);
}
}
}
21.11.2014 Processing sketches
P06 Strings and Chars
/*
P06 Strings and Chars
This example illustrates how to work with Strings (a collection of characters)
and how to display text on the screen. Also it shows how to access single characters
of a string by using the charAt() function.
*/
// Initialize a new string variable and assign the phrase "HELLO" to it
String word = "HELLO";
// Variable to count the current character position
int index = 0;
void setup() {
size(1000, 600);
// Set the size for any text that is drawn to 36px
textSize(36);
// Reduce the frame rate of the draw() loop to 2 frames per second
frameRate(2);
}
void draw() {
background(0);
// Make sure that the index never exceeds the bounds of the word
if (index >= word.length() ) {
index = 0;
}
// Display the character at the current position (index) at the center of the screen
text(word.charAt(index), width*0.5, height*0.5);
// Increment the index by 1
index++;
}
P07 Array Layout
/*
P07 Array Layout
This sketch shows how Arrays can be used to structure a set of numbers.
Also it uses a for-loop to iterate the Array and to access each individual
number of it to draw an ellipse with the respective diameter.
*/
// Initialize an Array to specify the individual diameters of ellipses in the grid.
// Note that the way of writing the numbers in a 3x3 grid is only for better readibility.
// One could also write {9,2,2,2,9,2,2,2,9}
int[] diameters = { 9,2,2,
2,9,2,
2,2,9 };
// Variable to define the spacing between the elements in the grid
int spacing = 50;
void setup(){
size(1000,600);
noFill();
// Print the total numbers of elements in the diameters array to the console
println(diameters.length);
}
void draw(){
background(255);
// Align the grid structure to the center
translate(width * 0.5 - (spacing * 1.5), height * 0.5 - (spacing * 1.5));
// Loop over the diameters array
for(int i=0; i < diameters.length; i++){
// Calculate the modulo of the division of the counter (i) by the total
// number of colums (3) to get the current column:
int x = (i % 3) * spacing;
// Calculate the actual row by dividing the counter by the total number
// of columns (3) and rounding it down with floor()
int y = floor(i / 3) * spacing;
// Draws the individual ellipse with the respective diameter
// specified in the diameters array.
ellipse(x, y, diameters[i], diameters[i]);
}
}
P08 Grid By Image
Make sure you have the Media:layout_pixels_example.png file in the data folder of the sketch!
/*
P08 Grid By Image
Example of how to load an image file into processing and how to access each
pixel of the image. The color information of the pixels of the loaded image
are used to modify the grid layout.
NOTICE: Make sure the image "layout_pixels_example.png" is placed in the "data" folder of
this sketch!
*/
// Initialize a variable to store an image
PImage img;
// Define a variable to specify the spacing of the elements
int spacing = 10;
void setup() {
size(1000, 600);
// Load the actual image file from the data folder and
// assign it to the img variable
img = loadImage("layout_pixels_example.png");
// How many pixels did we load?
println(img.pixels.length);
}
void draw() {
background(0);
// Only show the actual image if a keyboard key is pressed
if(keyPressed){
image(img, 0, 0);
}
// Two nested for-loops to draw ellipses all over the window
// with a certain spacing
for (int x=0; x < width; x+= spacing) {
for (int y=0; y < height; y+= spacing) {
// Extract the color of the x and y pixel position of the image
color c = img.get(x, y);
// Only actually draw an ellipse when the current brightness of the
// extracted color is very dark (brightness == 0)
if (brightness(c) == 0 ) {
ellipse(x, y, 5, 5);
}
}
}
}
28.11.2014 Processing sketches
P09 Interval timer
Make sure you have the files Media:interval_pixels_example_A.png, Media:interval_pixels_example_B.png and Media:interval_pixels_example_C.png in the data folder of the sketch!
/*
P09 Interval timer
A refinement of the "Grid by image" example with multiple changing
images. The millis() function is utilized to create an interval
timer which changes the actual image from the image sequence stored
in an array. The mouse x position changes the size of the grid dynamically.
Therefor the map() function is used to scale the range of the screen
width to the desired range for controlling the grid size.
*/
float gridSize = 10;
// Array of images (of type PImage) with the size
// of 3 is initializied
PImage[] images = new PImage[3];
// Counter for the current index of the image sequence
int imageCounter = 0;
// Variable to define the timer interval in milliseconds
int timerInterval = 400;
// Helper variable to store the last time the interval time has passed
int lastMillis = 0;
void setup() {
size(1000, 600);
// Assign individual images from the data folder
// to the array positions
images[0] = loadImage("interval_pixels_example_A.png");
images[1] = loadImage("interval_pixels_example_B.png");
images[2] = loadImage("interval_pixels_example_C.png");
}
void draw() {
background(0);
// The millis() function returns the number of milliseconds
// (thousandths of a second) since starting the program.
// When lastMillis is substracted from millis(), we get the
// milliseconds which have been past since the last timer execution.
if( millis() - lastMillis > timerInterval ){
// Now count up the imageCounter by 1
imageCounter++;
// Make sure it stays within the bounds of the images array
imageCounter = imageCounter % images.length;
// It is important to set lastMillis to the actual number
// of milliseconds, otherwise the if condition does not
// work repetitively.
lastMillis = millis();
}
// Helper variable to store the actual image from the array.
PImage currentImg = images[imageCounter];
// Only show the background image when a keyboard key is pressed
if(keyPressed){
image(currentImg, 0, 0);
}
// Dynamically scale the gridSize according to the mouse
// x position
gridSize = map(mouseX, 0, width, 5, 30);
// Loop through the columns and rows of the grid
// as in the previous example
for (int x=0; x < width; x+= gridSize) {
for (int y=0; y < height; y+= gridSize) {
color c = currentImg.get(x, y);
if (brightness(c) < 255 ) {
ellipse(x, y, 5, 5);
}
}
}
}
P10 Linear movement and direction
/*
P10 Linear movement and direction
The famous "bouncing ball"illustrates how steady movement
is achived by adding a constant number (speed) to the actual
position of an ellipse. The horizontal or vertical direction
is changed when the ellipse hits an edge of the sketch window.
*/
float rad = 60.0;
float xpos, ypos;
float xspeed = 2.8;
float yspeed = 2.2;
int xdirection = 1;
int ydirection = 1;
void setup()
{
size(640, 360);
noStroke();
frameRate(30);
ellipseMode(RADIUS);
xpos = width/2;
ypos = height/2;
}
void draw()
{
background(102);
xpos = xpos + ( xspeed * xdirection );
ypos = ypos + ( yspeed * ydirection );
if (xpos > width-rad || xpos < rad) {
xdirection *= -1;
}
if (ypos > height-rad || ypos < rad) {
ydirection *= -1;
}
ellipse(xpos, ypos, rad, rad);
}
P11 Polar dots
/*
P11 Polar dots
Illustrates how circular shapes and movements are created by using
polar coordinates (angle and radius) and how to convert these to cartesian
coordinates (x and y) by using sine and cosine functions (sin() and cos()).
*/
// Radius
float r;
// Radius offset
float rOffset = 1.0;
// Angle and speed
float angle = 0.0;
float angleSpeed = 0.02;
void setup() {
size(1000, 600);
ellipseMode(CENTER);
// Set r according to the sketch height
r = height * 0.25;
background(255);
}
void draw() {
// Dynamically scale the radius with the mouse x position
rOffset = map(mouseX, 0, width, 0.0, 1.5);
// Draw a semi-transparent rectangle across the whole window
// to let the backround smoothly fade out.
fill(255,10);
rect(0,0,width,height);
// Move to the center
translate(width/2, height/2);
// Convert polar to cartesian coordinates
// and scale the actual radius
float x = (r * rOffset) * cos(angle);
float y = (r * rOffset) * sin(angle);
// Draw the moving red ellipse to the actual position
noStroke();
fill(200,0,0);
ellipse(x, y, 17, 17);
// Draw the steady circle
stroke(0,10);
noFill();
ellipse(0,0,r*2,r*2);
// Increase the current value of angle by the value of angleSpeed
angle += angleSpeed;
}