Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Processing 2: Creative Programming Cookbook
Processing 2: Creative Programming Cookbook

Processing 2: Creative Programming Cookbook:

eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Processing 2: Creative Programming Cookbook

Chapter 1. Getting Started with Processing 2

In this chapter we will cover:

  • Installing Processing on your computer

  • Exploring the Processing Development Environment

  • Installing libraries

  • Installing tools

  • Switching modes

  • Understanding the coordinate system

  • Writing your first Processing sketch

  • Using math functions

  • Responding to mouse events

  • Responding to keyboard events

Introduction


In this chapter, we'll take a look at the very basics of Processing. You'll learn how to install Processing on your computer, and extend it with libraries and tools. We'll also take a glimpse at the different modes that are available in Processing 2. These things aren't very exciting, but you need to know about them before you can start creating interactive art.

But don't worry, you'll have written your first Processing sketches by the time you reach the end of the chapter. You will learn more about the structure of a Processing sketch, and we'll use some math along the way. These sketches will also teach you the basics of interaction between humans and computers. We'll use the mouse and keyboard to create simple, yet somewhat useful applications. You'll notice that programming in the Processing language probably isn't as hard as you may have thought.

Installing Processing on your computer


Processing is an open source programming language and environment. It can be used to create images, interactive installations, smartphone applications, and even 3D printed objects. Just about anything you can imagine. In this recipe, we'll take a look at installing Processing on Mac OS X, Windows, and Linux.

Getting ready

Download Processing 2 for your operating system at http://processing.org/download/. Processing is available for Windows, Mac OS X, and Linux. Processing for Windows comes in two flavors, one with Java and one without. Download the one with Java if you aren't sure which one to choose.

How to do it...

  • Windows: Unzip the file you've downloaded to C:\Program Files. You'll find the Processing application at C:\Program Files\Processing\. You might want to create a desktop shortcut to this app so it's easily available.

  • Mac OS X: Unzip the file you've downloaded and drag the Processing application to your Applications folder.

  • Linux: Unzip the folder to your Documents folder. Processing for Linux is a shell script. You can double-click this script and click the Run button to start Processing.

How it works...

The Processing language is built on top of Java, so you'll need a Java runtime on your computer for it to work. All versions of Mac OS X prior to 10.7 had a Java runtime installed by default. Starting with 10.7, Apple removed this. But don't worry. When you start Processing for the first time, the OS will ask you to install a Java runtime if you haven't done that already.

Processing for Windows and Linux comes with a java directory that contains everything you need to run Processing. You can however choose to use another Java runtime if you've installed one on your machine. But you should only do this if you are an advanced user and familiar with Java on one of these platforms.

There's more...

Processing uses a folder called the Sketchbook, where you will keep your sketches, libraries, and tools. Best practice is to keep this Sketchbook folder in the standard place for your OS.

  • Mac OS X: /username/Documents/Processing/

  • Windows: C:\Documents and Settings\username\My Documents\Processing\

  • Linux: /home/username/sketchbook/

Exploring the Processing Development Environment


When you start to work with a new application, it's important to understand the interface. In this recipe, we'll take a look at the Processing Development Environment, sometimes referred to as PDE.

How to do it...

This is the easiest thing you'll do in this book. Just open the Processing application. The following screenshot shows you what the PDE looks like on Mac OS X:

How it works...

When you open the Processing app, you'll notice that the PDE is a very basic programming environment. If you are an experienced programmer, you might miss a lot of features. The PDE was designed like this, so that people without any programming experience can get started with exploring code without having to worry about project settings, or learning a difficult interface. Let's take a look at the different interface elements.

  1. This is the run button. If you click this button, it will compile your code, and run your sketch in a new window. The shortcut for running your code is Cmd + R on the Mac, and Ctrl + R on Windows and Linux. Alternatively, you can hold down the Shift key while clicking this button to present your sketch. This will run your sketch centered on a gray fullscreen background.

  2. The stop button will terminate your sketch. You can also press the Esc key on your keyboard.

  3. Clicking the new button will create a new Processing sketch in the current window. If you want to create a sketch in a new window, you can use the File | New menu.

  4. The open button will open a menu with the names of all sketches in your sketchbook folder. This will open a sketch in the current window. If you want to open a sketch in a new window, you can use the File | Open menu.

  5. The save button will open a dialog to save your sketch.

  6. The export button will compile your sketch as an application. Holding down the Shift key will export your sketch as a Java Applet. You'll learn more about exporting your sketches in the Exporting applications in Chapter 5, Exporting from Processing recipe.

  7. This is the text editor where you will type your code.

  8. The message area is used by Processing to display messages when you save or export our sketch, or when you made a syntax error while coding.

  9. The console is used to display more detailed error messages. The output of the print() and println() functions will also appear here. You'll learn more about these functions in the Using math functions recipe later in this chapter.

Installing libraries


The core functionality of Processing is very basic. This was done by design, to make it easy for everyone to get started using it. If you need to do something that's not available in Processing, you can use a library that adds the functionality you need. One of the new features in Processing 2 is the Library Manager. This allows you to install new libraries in the easy way.

Getting ready

There is an overview of the available Processing libraries on the Processing website at http://processing.org/reference/libraries/. You'll find the documentation of the libraries included with Processing and a list with contributed libraries. There are libraries to work with 3D, computer vision, geometry, and a lot more.

How to do it...

You can open the library manager by using this menu: Sketch | Import Library… | Add Library…. This will give you a list of available libraries. To install the library you need to select it from the list and click on the Install button. Processing will install the library in the libraries folder of your sketchbook.

Unfortunately, not all libraries are included in this list. Some of the older libraries will probably still work in Processing 2, but the developer might not have added the new functionality to install the library through the Library Manager. In that case, you'll need to install the library manually. Don't worry; this is not as hard as it sounds.

You should download the library from the website of the developer and unzip it. Drag this folder to the libraries folder inside your sketchbook. Libraries are structured in a (predefined) way. If the library is not structured like this, it won't work. The main library folder usually contains four subfolders: examples, library, reference, and src. The examples folder contains Processing sketches the developer made to show how the library works. The library folder contains the compiled library code that will be imported into your sketch. The reference folder stores the documentation on how to use the library. The src folder contains the source code of the library. This might be handy for advanced users to learn how the library works and modify it as per their needs.

How it works...

The folder structure for libraries is important for Processing to find the library. The main folder for the colorLib library is named colorLib. Inside the library folder within that directory, you'll find a file named colorLib.jar. This JAR file will be included in your applet or application when you export your sketch. You can add import libraries into your sketch by going to the Sketch | Import Library… menu and select the library you want.

Installing tools


Processing tools are little applications that extend the PDE. Processing comes with a standard set of tools: a color selector, a tool to create fonts, a tool to create movies, and some other useful things.

Getting ready

There is an overview of available tools on the Processing website at http://processing.org/reference/tools/. This overview includes all standard tools and tools made by people from the Processing community. At the moment, there aren't that many tools available, but the number of quality tools might grow in the future.

How to do it...

Processing 2 has a new feature to install tools in an easy way: the Tool Manager. You can find the Tool Manager by going to Tools | Add Tool…. The Tool Manager works the same way as the Library Manager we've discussed in the Installing libraries recipe. Just like with libraries, not all tools are available in the Tool Manager. If you find a tool online, you can install it manually in the tools directory. This procedure is the same as installing a library manually. The Tool Manager looks as shown in the following screenshot:

How it works...

Tools are installed in the tools directory in your sketchbook. Each tool directory usually contains two directories, one for the tool, which contains the tool JAR file, and one with the Java source code. This JAR file is executed from the tool menu.

Switching modes


When Processing first came out, there was only the standard Java mode. But a lot has changed over recent years. The Processing language was ported to JavaScript by John Resig to show the capabilities of the HTML5 canvas element. Processing 2 also enables you to create apps for the Android operating system.

Getting ready

Open the Processing app. You probably already did that, since you're reading this book.

How to do it...

In the upper-right corner of the PDE, you'll see a button with the text STANDARD. If you click it, you'll get a small menu to select the other modes. Processing 2 comes with three modes: Standard, Android, and JavaScript. There is also an Add Mode… option in the menu, which will open the Mode Manager. This Mode Manager works in a similar way to the Library Manager and the Tool Manager.

How it works...

If you run a sketch in Standard mode, the PDE will compile your code and run it as a Java applet. This mode is useful if you want to create native applications that will run on a computer. Running a sketch in JavaScript mode will start a local web server on your computer, and open your default browser so you can see the sketch run within a HTML5 page. Android modewill run the sketch in the Android Emulator or on your Android device.

Note

You'll need to install the Android SDK to make this work. The color scheme of the PDE is also different in Android mode, so it's a little easier to see in which mode you are.

See also

This book also covers the new JavaScript and Android modes in depth. You can learn all about it in Chapter 9, JavaScript Mode, and Chapter 10, Exploring Android Mode.

Understanding the coordinate system


Before you can draw things to the screen, you need to know how the coordinate system works. Design applications might use a different point for the origin of their drawing surface. For instance, Photoshop uses the upper-left corner as (0,0), while Illustrator uses the bottom-left corner as (0,0).

Getting ready

Open Processing and create a new sketch.

How to do it...

Type this line of code in the Processing editor and press the run button. You can also use Ctrl + R (Windows, Linux) or Cmd + R (Mac OS X) to run your sketch.

size( 400, 300 );

How it works...

Processing uses the upper-left corner for the origin of the window. The size() function sets the dimensions of your sketch window. The first parameter is used to set the value of the system variable width, the second parameter is used to set the value of the system variable height.

Imagine that you want to draw a point at the bottom-right corner of the window. If you were to draw that point at (400, 300), you won't see anything on your screen. You need to draw your point at (width-1, height-1) to make it visible on screen. This may look a little strange, but it's actually very logical. If you want to draw a point at the origin, you'll use: point(0, 0);. This line of code will fill the first pixel on the first row. As we start counting at 0, the last pixel on that row would be 399, or width-1. The same is true for the height. The following screenshot shows our window of 400 by 300 pixels, divided into squares of 50 x 50 pixels.

Writing your first Processing sketch


In the previous recipes, you've learned all the boring stuff such as installing Processing and libraries. It's time to get your hands dirty now and write some code.

Getting ready

Create a new Processing sketch and save it as my_first_sketch to your sketch folder.

How to do it...

This is the full code for your first sketch. This sketch will draw some lines and points with varying stroke weights.

void setup()
{
  size( 640, 480 );
  smooth();
}

void draw()
{
  background(255);
  
  strokeWeight( 1 );
  point( 20, height/1.5 );
  line( 70, 20, 70, height - 20 );
  strokeWeight( 2 );
  point( 120, height/1.75 );
  line( 170, 20, 170, height - 20 );
  strokeWeight( 4 );
  point( 220, height/2 );
  line( 270, 20, 270, height - 20 );
  strokeWeight( 8 );
  point( 320, height/3 );
  line( 370, 20, 370, height - 20 );
  strokeWeight( 16 );
  point( 420, height/4 );
  line( 470, 20, 470, height - 20 );
  strokeWeight( 32 );
  point( 520, height/5 );
  line( 570, 20, 570, height - 20 );
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

If you run the sketch, you'll see the results of your hard work. It will look as shown in the following screenshot:

How it works...

In this recipe, you've learned the most basic functions to create a simple Processing sketch. Let's take a deeper look at what these functions do:

  • The setup() function is called only once when you run your sketch. You'll use this function to set the size of your sketch, add values to some variables, load images, and so on.

  • The draw() function is called continuously, at a rate of 60 frames per second.

  • The size() function sets the size of your sketch window. You can use size( screenWidth, screenHeight ) to create a sketch with dimensions that match the resolution of your computer screen.

  • The smooth() function is used to enable anti-aliasing. This means that all your shapes will have a soft edge. If you don't use this function, the shapes will have a more jagged edge.

  • The point() function is used to draw a point on the screen. The first parameter is the x-coordinate, the second one is the y-coordinate of the point you want to draw.

  • The line() function is used to draw a line on the screen. To draw a line, you basically need two points to define that line, as you might remember from math class in high school. The first two parameters of this function are the x and y coordinates of the first point, the third and fourth parameters are the x and y coordinates of the second point.

  • The strokeWeight() function will change the appearance of the shape you'll draw to the screen. The parameter will set the width of the stroke. For example, you can use strokeWeight(4) to draw a line with a thickness of 4 pixels.

There's more...

Processing sketches have a specific folder structure. If you save your sketch as my_first_sketch, you'll find a folder with this name in your Processing sketchbook. Inside this folder, you'll find a file named my_first_sketch.pde. Processing uses this folder structure to keep everything it needs to run the sketch together. This will be very handy when you write more complicated sketches that use more code files, or other data such as images or fonts.

Using math functions


You'll likely use some basic math when writing sketches with Processing. Don't worry if you forgot some of the math you learned in school, the Processing language comes with some handy functions that can do the hard work for you. But you might need to sharpen your math skills if you want to use these functions for some more advanced things such as data visualization.

Getting ready

We're going to write a small sketch that uses some of the math functions. The output of the app will be logged to the console. Start by creating a new sketch and save it as math_functions.pde.

How to do it...

This is the full code for the application we are going to write. We'll start by declaring some integer and float variables. The numbers variable is an array of floats containing the values of the variables we declared before. This sketch uses the println() function to log the output of the abs(), ceil(), floor(), round(), sq(), sqrt(), min(), max(), and dist() functions to the console.

int x = 177;
int y = -189;
float a = 32.75;
float b = -70.38;

float[] numbers = {a, b, x, y};

println("The absolute value of " + a + " is " + abs(a) );
println("The absolute value of " + b + " is " + abs(b) );
println("The absolute value of " + y + " is " + abs(y) );
println("The closest int value greater than (or equal to) " + x + " is " + ceil(x) );
println("The closest int value greater than (or equal to) " + a + " is " + ceil(a) );
println("The closest int value greater than (or equal to) " + b + " is " + ceil(b) );
println("The closest int value less than (or equal to) " + y + " is " + floor(y) );
println("The closest int value less than (or equal to) " + a + " is " + floor(a) );
println("The closest int value less than (or equal to) " + b + " is " + floor(b) );
println("The closest int value to " + a + " is " + round(a) );
println("The closest int value to " + b + " is " + round(b) );
println("The square number of " + x + " is " + sq(x) );
println("The square number of " + b + " is " + sq(b) );
println("The square root of " + x + " is " + sqrt(x) );
println("The square root of " + a + " is " + sqrt(a) );
println("The square root of " + b + " is " + sqrt(b) );
println("The smallest number in the list {" + a + "," + b + "," + x + "," + y + "} is " + min( numbers ) ); 
println("The largest number in the list {" + a + "," + b + "," + x + "," + y + "} is " + max( numbers ) ); 
println("The distance between (" + x + ", " + y + ") and (" + a + ", " + b + ") is " + dist(x, y, a, b ) );

If you run the sketch, you'll see that Processing will show an empty gray window of 100 x 100 pixels. This is the standard window size Processing uses if you don't use the size() function in a sketch. The output of the application will look as shown in the following screenshot:

How it works...

You've learned a lot of new functions to work with numbers in this recipe. Let's take a look at what they do:

  • abs() calculates the absolute value of the parameter. The result is always a positive number, so abs(-189) will return the number 189.

  • ceil() returns the closest integer value, greater than or equal to the value of the parameter. For instance, ceil(177) will return 177, ceil(-70.38) will return -70.

  • floor() returns the closest integer value, less than or equal to the value of the parameter. floor(32.75) will return 32, floor(-70.38) will return -71.

  • round() returns the closest integer value to the parameter. round(32.75) will return the number 33, round(-70.38) will return -70.

  • min() returns the smallest number from the list used as the parameter.

  • max() returns the largest number from the list used as the parameter.

  • sq() returns the square of a number. This is the same as multiplying the value of the parameter by itself. Using this function will always result in a positive number.

  • sqrt() returns the square root of a number. The value of the parameter should always be a positive number. sqrt(-70.38) will return NaN (short for Not a Number).

  • dist() calculates the distance between two points. The first two parameters are the x and y coordinates of the first point, and the third and fourth parameters are the x and y coordinates of the second point. The dist() function uses the distance formula, which is derived from the Pythagorean theorem.

There's more...

The println() function is really handy to debug your sketches. You'll use it a lot to log the value of a variable to the console. For instance, println(a) will log the value of variable a to the console. But you can also combine variables and even other functions inside the println() function, just like we did in the code for this small sketch. Let's take a look at how you can do this.

println( x + y );

This line will print the number -12 to the console. The + operator has precedence over the println() function, so the calculation will be performed first, before the println() function is executed.

println( x + " " + y );

This line will print 177 -189 to the console, and is the easiest way to print the values of the two variables to the console. In this example, the + sign inside the println() function is used to combine the values of the two variables together with the space between the two quotes into a variable of the type String.

Responding to mouse events


When you interact with a computer, you'll probably use a mouse. This is a standard input device on all computers that use a graphical user interface (GUI). The mouse became popular in the 1980s when Apple released the Macintosh. Most people know how to use a mouse, or trackpad, so you can easily use this to create art for people to interact with.

How to do it...

This is the full code for the sketch.

Note

Here, the draw() function is empty, as we'll do all the drawing with the mouse functions. We do need to add the draw function though, as it is used to make our app run continuously. If we leave it out of the code, the code in setup() will only run once and the app won't be interactive.

void setup()
{
  size( 640, 480 );
  smooth();
  background( 255 );
}

void draw()
{
  // empty, but we need it to create an app that runs in the continuous mode.
}

void mousePressed()
{
  if ( mouseButton == RIGHT ) {
    background( 255 );
  }
}

void mouseMoved()
{
  stroke( 0, 64 );
  strokeWeight( 1 );
  fill( 255, 32 );
  float d = dist( mouseX, mouseY, pmouseX, pmouseY );
  constrain( d, 8, 100 );
  ellipse( mouseX, mouseY, d, d );
}

void mouseDragged()
{
  stroke( 0 );
  float d = dist( mouseX, mouseY, pmouseX, pmouseY );
  constrain( d, 0, 100 );
  float w = map( d, 0, 100, 1, 10 );
  strokeWeight( w );
  line( mouseX, mouseY, pmouseX, pmouseY );
}

void mouseReleased()
{
  noStroke();
  fill( 255, 16 );
  rect( 0, 0, width, height );
}

void mouseClicked()
{
  fill( 255, 0, 0, 128 );
  float d = random( 20, 200 );
  ellipse( mouseX, mouseY, d, d );
}

After typing this code, you can run your sketch by clicking the run button or using the shortcut Cmd + R on the Mac or Ctrl + R on Windows and Linux. You can now start drawing with your mouse. When you move your mouse, you'll leave a trail of circles. When you press the mouse button and release it, you'll draw a red circle. When you move the mouse while pressing the left mouse button, you'll draw a black stroke. You can use the right mouse button to erase the screen and start all over again. The output of the application might look similar to the following screenshot:

How it works...

There are five functions and six system variables you can use to track mouse interaction in your sketch:

  • The mouseClicked() function is executed when you click a mouse button. This means pressing the button and releasing it. In the application you just made, this function was used to draw the transparent red circle.

  • The mouseDragged() function is executed when you press a mouse button and move the mouse while the button is pressed. This function is used to draw the lines in our sketch.

  • The mouseMoved() function is called every time the mouse is moved while no buttons are pressed. In our sketch, this leaves a trail of white transparent circles with a transparent black border.

  • The mousePressed() function is called when you press the button on your mouse. We use this function, together with the system variable mouseButton, to clear the screen if the right mouse button was pressed.

  • The mouseReleased() function is called when you release the mouse button. We used this function in our sketch to draw a transparent white rectangle with the size of the window on top of everything.

  • The system variable mouseX contains the current x coordinate of the mouse within the sketch window. This variable is updated every frame.

  • The system variable mouseY contains the current y coordinate of the mouse within the sketch window. This variable is updated every frame.

  • The system variable pmouseX contains the x coordinate of the mouse in the previous frame. This variable is updated every frame.

  • The system variable pmouseY contains the y coordinate of the mouse in the previous frame. This variable is updated every frame.

  • The system variable mousePressed is a boolean variable that keeps track if a mouse button is pressed or not. The value of this variable is true if a mouse button is pressed and false if no buttons are pressed.

  • The system variable mouseButton is a variable used to keep track of which mouse button is pressed. The value of this variable can be LEFT, RIGHT, or CENTER.

Responding to keyboard events


Another form of human-computer interaction is the keyboard. Next to the mouse, this is also one of the best-known devices to interact with computers. You can easily detect when a user presses a key, or releases it again, with Processing. One of the great things is that you can assign keys programmatically to execute pieces of code for you. This is one of the easiest ways to create a simple user-interface with Processing. For instance, you could use the D key to toggle a debug mode in your app, or the S key to save the drawing you made as an image.

How to do it...

We'll start by declaring some variables and writing the setup() and draw() functions. In this recipe, we'll write a basic Processing sketch that will change the values of the variables we've declared when we press certain keys on the keyboard.

int x;
int y;
int r;
color c;
boolean drawStroke;

void setup()
{
  size( 480, 320 );
  smooth();
  strokeWeight( 2 );
  
  x = width/2;
  y = height/2;
  r = 80;
  c = color( 255, 0, 0 );
  drawStroke = true;
}

void draw()
{
  background( 255 );
  
  if ( drawStroke == true ) {
    stroke( 0 );
  } else {
    noStroke();
  }

  fill( c );
  ellipse( x, y, r*2, r*2 );
}

The next code we'll write are the functions that will take care of the keyboard events. There are three functions we can use: keyPressed() , keyReleased() , and keyTyped().

void keyPressed()
{
  if ( key == CODED ) {
    if ( keyCode == RIGHT ) {
      x += 10;
    } else if ( keyCode == LEFT ) {
      x -= 10;
    } else if ( keyCode == UP ) {
      y -= 10;
    } else if ( keyCode == DOWN ) {
      y += 10;
    }
  }
  
  x = constrain( x, r, width-r );
  y = constrain( y, r, height-r );
  
}

void keyReleased()
{
  switch ( key ) {
    case 'r':
      c = color( 255, 0, 0 );
      break;
    case 'g':
      c = color( 0, 255, 0 );
      break;
    case 'b':
      c = color( 0, 0, 255 );
      break;
    case 'c':
      c = color( 0, 255, 255 );
      break;
    case 'm':
      c = color( 255, 0, 255 );
      break;
    case 'y':
      c = color( 255, 255, 0 );
      break;
    default:
      break;
  }
}
void keyTyped()
{
  if ( key == 's' ) {
    drawStroke = !drawStroke;
  }
}

The result of this application looks as shown in the following screenshot:

You can use the arrow keys to move the ball around. The S key will toggle the stroke. The R, G, B, C, M, and Y keys will change the color of the ball.

How it works...

There are three different functions that catch key events in Processing: keyPressed(), keyReleased(), and keyTyped(). These functions behave a little differently. The keyPressed() function is executed when you press a key. You should use this one when you need direct interaction with your application. The keyReleased() function is executed when you release the key. This will be useful when you hold a key and change something in your running application when the key is released. The keyTyped() function behaves just like the keyPressed() function, but ignores all special keys such as the arrow keys, Enter, Ctrl, and Alt.

  • The system variable key contains the value of the last key that was pressed on the keyboard.

  • The system variable keyCode is used to detect when special keys such as Shift, Ctrl, or the arrow keys are pressed. You'll most likely use this one within an if-statement that checks if the key is CODED, just like you did in the keyPressed() function in the example. The value of keyCode can be UP, DOWN, LEFT, RIGHT, ALT, CONTROL, SHIFT, BACKSPACE, TAB, ENTER, RETURN, ESC, or DELETE.

  • The system variable keyPressed is a boolean variable. The value of this variable is true if a key on the keyboard is pressed and false if no keys are pressed. This is a handy variable to use inside the draw() function.

  • The keyPressed() function is executed once when you press a key.

  • The keyReleased() function is executed once when you release a key.

  • The keyTyped() function is executed when you type a key. Keys like Alt, Ctrl, or Shift are ignored by this function.

There's more...

You've just learned how to react to single key presses. If you want to do something when a user presses multiple keys (shortcuts such as Ctrl + S to save an image), it won't work with these standard functions. There is an excellent article on the Processing Wiki that describes strategies for detecting multiple key presses at http://wiki.processing.org/w/Multiple_key_presses.

Left arrow icon Right arrow icon

Key benefits

  • Explore the Processing language with a broad range of practical recipes for computational art and graphics
  • Wide coverage of topics including interactive art, computer vision, visualization, drawing in 3D, and much more with Processing
  • Create interactive art installations and learn to export your artwork for print, screen, Internet, and mobile devices

Description

Processing is probably the best known creative coding environment that helps you bridge the gap between programming and art. It enables designers, artists, architects, students and many others to explore graphics programming and computational art in an easy way, thus helping you boost your creativity. "Processing 2: Creative Programming Cookbook" will guide you to explore and experience the open source Processing language and environment, helping you discover advanced features and exciting possibilities with this programming environment like never before. You'll learn the basics of 2D and 3D graphics programming, and then quickly move up to advanced topics such as audio and video visualization, computer vision, and much more with this comprehensive guide. Since its birth in 2001, Processing has grown a lot. What started out as a project by Ben Fry and Casey Reas has now become a widely used graphics programming language. Processing 2 has a lot of new and exciting features. This cookbook will guide you to explore the completely new and cool graphics engine and video library. Using the recipes in this cookbook, you will be able to build interactive art for desktop computers, Internet, and even Android devices! You don't even have to use a keyboard or mouse to interact with the art you make. The book's next-gen technologies will teach you how to design interactions with a webcam or a microphone! Isn't that amazing? "Processing 2: Creative Programming Cookbook" will guide you to explore the Processing language and environment using practical and useful recipes.

Who is this book for?

This book targets creative professionals, visual artists, designers, and students who have a starting knowledge of the Processing Development environment and who want to discover the next level of Processing. Anyone with a creative practice who wants to use computation in their design process. A basic understanding of programming is assumed. However, this book is also recommended to the non-artistic, looking to expand their graphics and artistic skills.

What you will learn

  • Draw expressive shapes and images in 2D and 3D and get inspiration for your creativity
  • Extend the possibilities with Processing using libraries that help you create interactive computational art
  • Play and control video files using some of the coolest recipes with unmatched techniques
  • Visualize music and even live audio
  • Build basic tools for audio visual performances
  • Interact with computers using a webcam
  • Create Processing sketches for the web using the new JavaScript mode
  • Create interactive applications for your Android devices
Estimated delivery fee Deliver to Slovenia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 20, 2012
Length: 306 pages
Edition : 1st
Language : English
ISBN-13 : 9781849517942
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Slovenia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Sep 20, 2012
Length: 306 pages
Edition : 1st
Language : English
ISBN-13 : 9781849517942
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 113.97
Processing 2: Creative Coding Hotshot
€37.99
Processing 2: Creative Programming Cookbook
€37.99
Mastering OpenCV with Practical Computer Vision Projects
€37.99
Total 113.97 Stars icon
Banner background image

Table of Contents

11 Chapters
Getting Started with Processing 2 Chevron down icon Chevron up icon
Drawing Text, Curves, and Shapes in 2D Chevron down icon Chevron up icon
Drawing in 3D–Lights, Camera, and Action! Chevron down icon Chevron up icon
Working with Data Chevron down icon Chevron up icon
Exporting from Processing Chevron down icon Chevron up icon
Working with Video Chevron down icon Chevron up icon
Audio Visualization Chevron down icon Chevron up icon
Exploring Computer Vision Chevron down icon Chevron up icon
Exploring JavaScript Mode Chevron down icon Chevron up icon
Exploring Android Mode Chevron down icon Chevron up icon
Using Processing with Other Editors Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(8 Ratings)
5 star 62.5%
4 star 12.5%
3 star 12.5%
2 star 12.5%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Lon Dec 20, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is really a fantastic book. Each of the 90 or so recipes includes a description, sample code, and a walk-through of how it works. Many of the sketches are simpler than I would like but that simplicity also makes them easy to follow. Along with that, references are given for outside resources, which makes the examples a useful launching point. This is definitely a 5-star book for anyone learning processing and I'd give it 4 stars as a useful reference for those who are already fairly proficient.
Amazon Verified review Amazon
Luis Hernández Nov 18, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent!
Amazon Verified review Amazon
Andrej May 02, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Bei diesem Buch gibt es fast nichts zu meckern:ProFür einsteiger und leicht fortgeschritteneSuper verständlich erklärt.wenn man fragen (fragen heist fragen zum programmieren) hat antwortet die firma einen auch (Klasse)Kontra:Naja es ist ein buch und bei mir war es so das ich mir dieses buch gekauft habe damit ich weiß wie man videos in processing abspielen kann naja und bei einer neueren version in processing ging das nicht da eine datei geändert wurde. Daher musste ich 2 wochen auf eine lösung warten aber ich habe sie einfach bequem und kostenfrei bekommen einfach super.Bücher halten nun mal einen gewissen stand x fest. da processing öfters verändert wird kann man nicht ganz erwarten das alles reibunglos leuft.
Amazon Verified review Amazon
M Pearson Dec 12, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I loved the no-nonsense approach of this book.As more and more Processing books hit the market, each new book has to think carefully about its approach, attempting to provide something that isn't already out there. Vantomme's book has taken this into account, being aimed squarely at the more advanced/impatient Processing user. It implicitly acknowledges that there are already plenty of great beginners guides out there, and that the reader has probably already read a few of them, which allows this book to speed through the hand-holding stage and get onto the meatier topics.The cookbook approach, chunking the teaching into manageable recipes of no more than a few pages each, makes it very easy to dip in and out of. And this conciseness means it can cover a lot more topics, in much fewer pages. I don't think there are any other Processing books that cover 3D, Computer Vision, Audio Viz, Android development, and writing your own libraries quite as succinctly as this.Highly recommended.
Amazon Verified review Amazon
RA Nov 30, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
At a GlanceJan Vantomme's Processing Cookbook bills itself as "Quick answers to common problems." In this regard, the author nicely succeeds in accomplishing that goal. The book is well organized, quite readable, and filled with many useful entry points for coders looking to jumpstart their projects. While it should not be the first book on Processing in your library (nor is it intended as such), it is a worthy addition for anyone wanting handy recipes that help serve up tasty procedural dishes.The AudienceThose who are new to both Processing and programming in general are probably advised to look elsewhere. However, it would be unfair to say that the book is beginner-hostile, as the first few chapters are a nice orientation in the Processing environment. Intermediate to advanced coders would probably have no difficulty using this as a suitable guide to getting started in the Processing language. Still, the main audience for this book is likely to be those who are already familiar with Processing, and can benefit from having a good set and a wide variety of starting points. This book would be at home in both the classroom and the individual bookshelf.The BookChapters progress gradually from beginning topics to more advanced ones. Each chapter follows a set structure and format which fosters a feeling of familiarity even for new topics. Readers move easily through a "Getting ready" section to the more detailed "How to do it..." section. Afterward, there is a review section "How it works...," and occasionally a "There's more..." or "See also" section for additional areas to explore. When encountering new material, it's nice to have these guideposts so the terrain never feels totally foreign.These are not in-depth tutorials. Like most recipe books, the idea is not to teach you how to cook, but to give you the ingredients and steps necessary to make something happen. You could choose to follow the instructions exactly, and get the same exact results, but the expectation is that you'll use these recipes to breeze through the tedium in order to focus on concocting your own special sauce.For my review, I used the digital version of the book. I installed a copy on my desktop setup (.pdf) and my iPad (eBook). While I generally prefer books in a physical format, programming and technical manuals can be unwieldy. With the digital version, I could easily switch between coding and reading on my desktop, and reading on the go with my tablet. In both environments, the layout is clear and legible, with the added benefit of being able to change document and content size as needed. The book design is easy on the eye, and avoids much of the ponderous density that plagues so many technical books.The CodeAll the code examples in the book are available for download. The book is written for Processing version 2.0, which as of this writing (late 2012) is still in beta. This means the examples are forward-looking, and should remain valid and useful for some time to come. The extra good news is that I tested the code in Processing 1.5.1, and found it to be mostly backward compatible as well. A very few sketches required slight modifications to run in the older version of Processing, but these tended to be obvious for the moderately experienced user. Exceptions to this were in the chapters on video, Android development, and writing libraries. For these, the user will need the more recent version of Processing.The code itself is generally easy to follow and nicely organized. Comments are minimal and unobtrusive, but present when you need them. There is nothing particularly flashy or clever -- the author seems much more interested in giving you a good set of workaday tools than showing off artsy syntax.The output as well is nothing fancy, just enough to make sure the sketch is working as intended, and not be completely without interest. Here again, there seems to be just the right balance in keeping you motivated while encouraging you to add your own creativity.CriticismsThere's not a lot to fault with this book. There are a few typos here and there, but these are not terribly distracting. Besides, there's a link in the preface for how and where to submit errata.Although the book generally flows nicely, the illustrations of the output come after the explanations. I found myself wanting to visually know ahead of time what the goal of a particular piece of code was. Of course, part of learning to program involves being able to look at code and visualize what is supposed to be happening, so in this regard the reader is being respected by not being spoon-fed.Sooner or later, everyone develops their own coding style and preference. I like variable names that are semantic even if they take longer to type and take up more space on the page. I have grown to dislike variable name choices that cause me to look around in other parts of the code to remind me what their meaning is supposed to be. In other words, the author's coding style is not an exact fit for my own, but of course there's nothing to keep me from editing any code I would use to conform to my own way of doing things.I also wish the downloaded code chapters were named as well as numbered, according to their chapter headings (sub-headings are, by the way). When needing to grab code quickly to start a new project, I'd rather not have dig randomly through the top level directory, or open the book just to find a pointer to what I already know I want. Again, I can easily rename these folders myself, but it would be nice not to have to.Am I being nit-picky? Yes, simply because the author and publisher left me no major targets to shoot at.ConclusionWhen I read a book on programming or any technical manual, I always have several questions in mind. Can I read it in a linear fashion? Can I easily find the part I need as a reference? Is the experience pleasurable, or at a minimum, painless? Is it well organized and non-intimidating to look at? Is the content useful? Am I learning something new, but still accessible? Does the author seem more interested in helping me than in showing off? Is this something I will want to pick up again and keep finding value?To all of these, I can answer "yes" for Processing 2: Creative Programming Cookbook. Much of the code will be helpful for current projects, and much of the rest served to help me know what to look forward to when I step up to Processing version 2.0. Several of the chapters covered areas that I have not yet spent much attention on... this book has definitely lowered the bar for entrance into these topics, while raising my enthusiasm the same time.Processing is a rapidly maturing technology, and we've arrived at the point where there are a number of good books on the subject. We are lucky to have the comprehensive reference books, the thorough-going text books, and the gorgeous gallery books. Now we also have a cookbook, exactly the sort of thing you want when you need more than the standard online reference, and less than the ponderous textbooks.Processing 2: Creative Programming Cookbook is not the only book on the subject you will want to own. But once you have it, I wouldn't be surprised if it's the one you wind up turning to first, and most often.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela