P5.js hello world This is the simplest p5.js block. Meant to be a starting point for others.
This tutorial is adapted from the book, Visualizing Data by Ben Fry, O'Reilly 2007. © 2007 Ben Fry. If you see any errors or have comments, please let us know.
Processing // Hour of Code™ // Computer Science Education Week // Code.org. 'Hello p5' was originally made as a 'trailer' for p5.js whereas 'Hello Processing' was made as a full one hour tutorial experience. In a fantasy world, we might end up with both of these things? For updating 'Hello p5' the 'trailer' a key priority is to feature the many, diverse contributors to p5.js and not have a singular voice presenting the library.
Ben Fry and Casey Reas
Processing is a simple programming environment that was created to make it easier to develop visually oriented applications with an emphasis on animation and providing users with instant feedback through interaction. The developers wanted a means to “sketch” ideas in code. As its capabilities have expanded over the past decade, Processing has come to be used for more advanced production-level work in addition to its sketching role. Originally built as a domain-specific extension to Java targeted towards artists and designers, Processing has evolved into a full-blown design and prototyping tool used for large-scale installation work, motion graphics, and complex data visualization.
Processing is based on Java, but because program elements in Processing are fairly simple, you can learn to use it even if you don't know any Java. If you're familiar with Java, it's best to forget that Processing has anything to do with Java for a while, until you get the hang of how the API works.
The latest version of Processing can be downloaded at http://processing.org/download
An important goal for the project was to make this type of programming accessible to a wider audience. For this reason, Processing is free to download, free to use, and open source. But projects developed using the Processing environment and core libraries can be used for any purpose. This model is identical to GCC, the GNU Compiler Collection. GCC and its associated libraries (e.g. libc) are open source under the GNU Public License (GPL), which stipulates that changes to the code must be made available. However, programs created with GCC (examples too numerous to mention) are not themselves required to be open source.
Processing consists of:
- The Processing Development Environment (PDE). This is the software that runs when you double-click the Processing icon. The PDE is an Integrated Development Environment (IDE) with a minimalist set of features designed as a simple introduction to programming or for testing one-off ideas.
- A collection of functions (also referred to as commands or methods) that make up the “core” programming interface, or API, as well as several libraries that support more advanced features such as sending data over a network, reading live images from a webcam, and saving complex imagery in PDF format.
- A language syntax, identical to Java but with a few modifications.
- An active online community, based at http://processing.org.
For this reason, references to “Processing” can be somewhat ambiguous. Are we talking about the API, the development environment, or the web site? We'll be careful in this text when referring to each.
Sketching with Processing
A Processing program is called a sketch. The idea is to make Java-style programming feel more like scripting, and adopt the process of scripting to quickly write code. Sketches are stored in the sketchbook, a folder that's used as the default location for saving all of your projects. Sketches that are stored in the sketchbook can be accessed from File → Sketchbook. Alternatively, File → Open... can be used to open a sketch from elsewhere on the system.
Advanced programmers need not use the PDE, and may instead choose to use its libraries with the Java environment of choice. However, if you're just getting started, it's recommended that you use the PDE for your first few projects to gain familiarity with the way things are done. While Processing is based on Java, it was never meant to be a Java IDE with training wheels. To better address our target audience, the conceptual model (how programs work, how interfaces are built, and how files are handled) is somewhat different from Java.
Hello world
The Processing equivalent of a 'Hello World' program is simply to draw a line:
Enter this example and press the Run button, which is an icon that looks like the Play button from any audio or video device. Your code will appear in a new window, with a gray background and a black line from coordinate (15, 25) to (70, 90). The (0, 0) coordinate is the upper left-hand corner of the display window. Building on this program to change the size of the display window and set the background color, type in the code below:
This version sets the window size to 400 x 400 pixels, sets the background to an orange-red, and draws the line in white, by setting the stroke color to 255. By default, colors are specified in the range 0 to 255. Other variations of the parameters to the stroke() function provide alternate results:
The same alternatives work for the fill() function, which sets the fill color, and the background() function, which clears the display window. Like all Processing functions that affect drawing properties, the fill and stroke colors affect all geometry drawn to the screen until the next fill and stroke functions.
Hello mouse
A program written as a list of statements (like the previous examples) is called a static sketch. In a static sketch, a series of functions are used to perform tasks or create a single image without any animation or interaction. Interactive programs are drawn as a series of frames, which you can create by adding functions titled setup() and draw() as shown in the code below. These are built-in functions that are called automatically.
The setup() block runs once, and the draw() block runs repeatedly. As such, setup() can be used for any initialization; in this case, setting the screen size, making the background orange, and setting the stroke color to white. The draw() block is used to handle animation. The size() function must always be the first line inside setup().
Because the background() function is used only once, the screen will fill with lines as the mouse is moved. To draw just a single line that follows the mouse, move the background() function to the draw() function, which will clear the display window (filling it with orange) each time draw() runs.
Static programs are most commonly used for extremely simple examples, or for scripts that run in a linear fashion and then exit. For instance, a static program might start, draw a page to a PDF file, and exit.
Most programs will use the setup() and draw() blocks. More advanced mouse handling can also be introduced; for instance, the mousePressed() function will be called whenever the mouse is pressed. In the following example, when the mouse is pressed, the screen is cleared via the background() function:
Exporting and distributing your work
One of the most significant features of the Processing environment is its ability to bundle your sketch into an application with just one click. Select File → Export Application to package your current sketch as an application. This will bundle your sketch as an application for Windows, Mac OS X, or Linux depending on which operating system you're exporting from. The application folders are overwritten whenever you export—make a copy or remove them from the sketch folder before making changes to the contents of the folder. Alternatively, you can turn off the automatic file erasure in the Preferences.
More about the export features can be found in the reference at http://processing.org/reference/environment/#Export
Creating images from your work
If you don't want to distribute the actual project, you might want to create images of its output instead. Images are saved with the saveFrame() function. Adding saveFrame() at the end of draw() will produce a numbered sequence of TIFF-format images of the program's output, named screen-0001.tif, screen-0002.tif, and so on. A new file will be saved each time draw() runs — watch out, this can quickly fill your sketch folder with hundreds of files. You can also specify your own name and file type for the file to be saved with a function like:
To do the same for a numbered sequence, use # (hash marks) where the numbers should be placed:
For high quality output, you can write geometry to PDF files instead of the screen, as described in the later section about the size() function.
Examples and reference
While many programmers learn to code in school, others teach themselves and learn on their own. Learning on your own involves looking at lots of other code: running, altering, breaking, and enhancing it until you can reshape it into something new. With this learning model in mind, the Processing software download includes hundreds of examples that demonstrate different features of the environment and API.
The examples can be accessed from the File → Examples menu. They're grouped into categories based on their function (such as Motion, Typography, and Image) or the libraries they use (PDF, Network, and Video).
Find an interesting topic in the list and try an example. You'll see functions that are familiar, e.g. stroke(), line(), and background(), as well as others that have not yet been covered. To see how a function works, select its name, and then right-click and choose Find in Reference from the pop-up menu (Find in Reference can also be found beneath the Help menu). This will open the reference for that function in your default web browser.
In addition to a description of the function's syntax, each reference page includes an example that uses the function. The reference examples are much shorter (usually four or five lines apiece) and easier to follow than the longer code examples.
Hello P5 Js
More about size()
The size() function sets the global variables width and height. For objects whose size is dependent on the screen, always use the width and height variables instead of a number. This prevents problems when the size() line is altered.
In the earlier examples, the size() function specified only a width and height for the window to be created. An optional parameter to the size() function specifies how graphics are rendered. A renderer handles how the Processing API is implemented for a particular output function (whether the screen, or a screen driven by a high-end graphics card, or a PDF file). The default renderer does an excellent job with high-quality 2D vector graphics, but at the expense of speed. In particular, working with pixels directly is slow. Several other renderers are included with Processing, each having a unique function. At the risk of getting too far into the specifics, here's a description of the other possible drawing modes to use with Processing.
The P2D renderer uses OpenGL for faster rendering of two-dimensional graphics, while using Processing's simpler graphics APIs and the Processing development environment's easy application export.
The P3D renderer also uses OpenGL for faster rendering. It can draw three-dimensional objects and two-dimensional object in space as well as lighting, texture, and materials.
The PDF renderer draws all geometry to a file instead of the screen. To use PDF, in addition to altering your size() function, you must select Import Library, then PDF from the Sketch menu. This is a cousin of the default renderer, but instead writes directly to PDF files.
Loading and displaying data
One of the unique aspects of the Processing API is the way files are handled. The loadImage() and loadStrings() functions each expect to find a file inside a folder named data, which is a subdirectory of the sketch folder.
Advanced Topic: Notes on the data folder The data folder addresses a common frustration when dealing with code that is tested locally but deployed over the web. Like Java, software written with Processing is subject to security restrictions that determine how a program can access resources such as the local hard disk or other servers via the Internet. This prevents malicious developers from writing code that could harm your computer or compromise your data. The security restrictions can be tricky to work with during development. When running a program locally, data can be read directly from the disk, though it must be placed relative to the user's “working directory,” generally the location of the application. When running online, data must come from a location on the same server. It might be bundled with the code itself (in a JAR archive, discussed later; or from another URL on the same server). For a local file, Java's FileInputStream class can be used. If the file is bundled in a JAR archive, the getResource() function is used. For a file on the server, URL.openStream() might be employed. During the journey from development to deployment, it may be necessary to use all three of these functions. With Processing, each of these scenarios (and some others) is handled transparently by the file API functions. By placing resources in the data folder, Processing packages the files as necessary for online and offline use. |
File handling functions include loadStrings(), which reads a text file into an array of String objects, and loadImage() which reads an image into a PImage object, the container for image data in Processing.
These examples may be a bit easier to read if you know the programming concepts of data types and classes. Each variable has to have a data type, such as String or PImage.
The String[] syntax means “an array of data of the class String.” This array is created by the loadStrings function and is given the name lines; it will presumably be used later in the program under this name. The reason loadStrings creates an array is that it splits the something.txt file into its individual lines. The following function creates a single variable of class PImage, with the name image.
To add a file to the data folder of a Processing sketch, use the Sketch → Add File menu option, or drag the file into the editor window of the PDE. The data folder will be created if it does not exist already.
To view the contents of the sketch folder, use the Sketch → Show Sketch Folder menu option. This opens the sketch window in your operating system's file browser.
Libraries add new features
A library is a collection of code in a specified format that makes it easy to use within Processing. Libraries have been important to the growth of the project, because they let developers make new features accessible to users without needing to make them part of the core Processing API.
Several core libraries come with Processing. These can be seen in the Libraries section of the online reference (also available from the Help menu from within the PDE.) These libraries can be seen at http://processing.org/reference/libraries/
One example is the PDF Export library. This library makes it possible to write PDF files directly from Processing. These vector graphics files can be scaled to any size and output at very high resolutions.
To use the PDF library in a project, choose Sketch → Import Library → pdf. This will add the following line to the top of the sketch:
Java programmers will recognize the import command. In Processing, this line is also used to determine what code is packaged with a sketch when it is exported as an applet or application.
Now that the PDF library is imported, you may use it to create a file. For instance, the following line of code creates a new PDF file named lines.pdf that you can draw to.
Each drawing function such as line() and ellipse() will now draw to the screen as well as to the PDF.
Other libraries provide features such as reading images from a camera, sending and receiving MIDI and OSC commands, sophisticated 3D camera control, and access to MySQL databases.
Sketching and scripting
Processing sketches are made up of one or more tabs, with each tab representing a piece of code. The environment is designed around projects that are a few pages of code, and often three to five tabs in total. This covers a significant number of projects developed to test and prototype ideas, often before embedding them into a larger project or building a more robust application for broader deployment.
P5 Js Game
The idea of sketching is identical to that of scripting, except that you're not working in an interpreted scripting language, but rather gaining the performance benefit of compiling to Java class files. Of course, strictly speaking, Java is itself an interpreted language, but its bytecode compilation brings it much closer to the 'metal' than languages such as JavaScript, Python, or Ruby.
Processing was never intended as the ultimate language for programming visuals; instead, we set out to make something that was:
- A sketchbook for our own work, simplifying the majority of tasks that we undertake.
- A programming environment suitable for teaching programming to a non-traditional audience.
- A stepping stone from scripting languages to more complicated or difficult languages such as full-blown Java or C++.
At the intersection of these points is a tradeoff between speed and simplicity of use. If we didn't care about speed, it might make sense to use Python, Ruby, or many other scripting languages. This is especially true for the education side. If we didn't care about making a transition to more advanced languages, we'd probably avoid a C++ or Java-style syntax. But Java makes a nice starting point for a sketching language because it's far more forgiving than C/C++ and also allows users to export sketches for distribution via the web.
Processing assembles our experience in building software of this kind (sketches of interactive works or it may seem.
Tutorials / p5.js Tutorials / Hello Worldtutorialp5.jsjavascripthello-worldNow that we know how to write P5.js code (using one of the editors we just talked about) and run it in a browser, we can start diving into the fun stuff.
Let’s start with an example program. Remember that P5.js requires a .html
file for the browser to render, so let’s start with that:
(You only have to create your own .html
file if you’re using a basic text editor. The other P5.js editors create this for you. I’d still recommend reading this section so you understand what’s going on behind the scenes though.)
This is just a very basic HTML file that doesn’t do anything yet. Save it to index.html
wherever you want. I’ll save mine to my desktop for now. You can open this up in your browser, but all you’ll see is a blank screen:
P5.js JavaScript Library
At its core, P5.js is a JavaScript library. Like we talked about in the JavaScript libraries tutorial, a JavaScript library is just a bunch of JavaScript code that was written by somebody else, that you can use from your own JavaScript code. For example, you can load the JQuery library to gain access to functions that make it easier to add interactive elements to your webpage. But keep in mind that it’s all just JavaScript code! In fact, you can look at the JQuery code here.
So when we say that P5.js is a JavaScript library, what we mean is that P5.js is a bunch of JavaScript code written by other people (these people to be more specific). We can load that library to give ourselves access to the functions that are defined in the library.
To load the P5.js JavaScript library, we add this line to the <head>
section of our index.html
file:
P5 Js Random
This line points to a copy of the p5.js
file, which contains all of the JavaScript code in the library. You can go that that URL in your browser to see the contents, but again, it’s all just regular JavaScript code!
We could also download the p5.js
file and put it next to our index.html
file, in which case we’d add this line instead:
(You should only do this if you need to work with P5.js offline or if you really want a self-contained project.)
Our .html
file now looks like this:
This file still doesn’t do anything, but now we have access to the functions that P5.js gives us. That means we can write JavaScript code that calls P5.js functions, like this:
We can put this code in its own sketch.js
file, and then add a <script src='sketch.js'></script>
line to the <head>
section of our index.html
file, or we can include the code directly in its own <script>
tag, like this:
Let’s take a second to talk about what this is really doing.
P5 Js Library
- The browser loads the
index.html
file and starts reading the HTML tags in it. - The browser reads the
<title>
tag, which sets the label displayed in the browser tab. - The browser reads the first
<script>
tag, which loads the P5.js library. - When the P5.js library is loaded, it defines a bunch of functions and sets up an
onload
callback. (More on that in a second.) - Then the browser reads the second
<script>
tag, which defines asetup()
and adraw()
function. - The browser finishes reading the HTML tags, which is just an empty
<body>
element. - The browser then fires the
onload
event, which triggers the callback that P5.js set up. - In that callback, P5.js creates an instance of the
p5
object and calls thesetup()
function that we created. - The
createCanvas()
function (which is a function that P5.js gave us) creates a canvas element and adds it to the<body>
tag. - The
background()
function (another function from P5.js) colors the whole canvas. In this case it’s gray. - P5.js automatically starts calling the
draw()
function 60 times per second. - Each frame, our code calls the
fill()
function, which changes the fill color to white. - Then our code draws a circle wherever the mouse is.
In other words, since the draw()
function is called 60 times per second, and each frame draws a circle wherever the mouse is, this program shows a trail of circles that follow the mouse.
Here’s a CodePen that shows the full HTML file we just saw:
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
And here’s a CodePen that just shows our JavaScript code:
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
From now on, I’m just going to show code like this without the surrounding HTML. But if you’re creating your own files, remember to include the HTML!
The P5.js Reference
Now we understand the basics of what P5.js is, what it’s doing behind the scenes, and how to write and run code that uses P5.js. We also know how we can use P5.js to create sketches:
- P5.js automatically calls the
setup()
function when the page loads. - We can call the
createCanvas()
function that P5.js gives us to create a<canvas>
element to draw on. - P5.js then automatically starts calling the
draw()
function 60 times per second. - We can call P5.js functions like
ellipse()
to draw stuff, and we can use P5.js variables likemouseX
andmouseY
to get input.
From here, it’s “just” a matter of knowing about other functions we can call and other variables we can use. Let me introduce you to your new best friend: **the P5.js reference!
The P5.js reference is a list of everything that P5.js gives you, and it should be your first stop when you have a question about how to do something in P5.js.
P5 Js Button
For example, let’s say we wanted to change our program to draw blue rectangles instead of white circles. How do we know what to do?
First off, we’d want to break our problem down into smaller pieces and take those pieces on one at a time. Step one might be: how do we change the color to blue?
We’d look in the reference, and we’d eventually find the fill()
function in the Setting
subdivision of the Color
section. We’d click the fill()
function link to view its reference page. That page tells us that one form of the fill()
function takes three arguments: red, blue, green, each between 0
and 255
. So to change the color to blue, we’d call fill(0, 0, 255)
! We might test that out by changing the circle’s color before we continue to the next step.
Then step two might be: how do we draw a rectangle? We’d go back to the P5.js reference, and after some searching, we’d find the rect()
function. We’d check out its reference page to learn that the rect()
function takes 4 parameters: an x position, a y position, a width, and a height. This is actually exactly what the ellipse()
function takes, so to draw a rectangle we’d just change the ellipse(mouseX, mouseY, 20, 20)
line to rect(mouseX, mouseY, 20, 20)
. Try changing the values of the parameters to see what happens!
Here’s what our code looks like now:
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
We could also do Google searches for stuff like “P5.js draw rectangle” for a ton of results. Remember: the best thing you can do is work in small steps!
Homework
- Modify the above program to draw a yellow triangle.
- Read through the P5.js reference and write small example programs to test different things out. If you have a question, don’t be afraid to post in the forum!
Next: Review
Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!