Animated Graphics Programming with JavaScript and p5.js
Open This Document
Link to this page: bit.ly/p5js-sp
Resources
- p5.js sketch template on repl.it
- p5.js Reference
- My YouTube playlist with videos for this class
- Color names, for use in background, stroke and fill
- JavaScript Guide
- My YouTube Channel with Programming Lessons
Welcome and Introduction
Your Teacher
I am Dave Briccetti (bri-’cheddy). I am a professional computer programmer who enjoys teaching programming to kids. I teach at three private schools, at the Lafayette Library occasionally, and I have individuals and small groups come to my house in Lafayette for lessons. (More)
Following Links
When you follow links from this document, holding Shift and Cmd while you click will open the page in a new tab and switch to that tab.
About This Course
JavaScript and p5.js
JavaScript is a popular programming language, especially for programs that run in a web browser.
p5.js is a JavaScript framework for combining animation, graphics, sound and art with programming.
Class Format
Our classes consist of:
- Instruction (Lectures)
- Exercises, where you practice what you’ve just learned, with specific goals
- Creative project work, where you apply what you’ve learned in your own way
- Show and tell, where we share our interesting creations
Parents
Many of your parents are likely excited about you learning programming at school. They will be curious about what we are doing. Please point them to this page, so they can follow along with us. Show them at home what you are learning in class. Explaining your programs to others can increase your understanding.
When You Finish
When you complete assigned work, there’s always more to do. You can
- Read the p5.js reference and learn about more features
- Look at p5.js examples
- Experiment, and make your own original creations
Computer Programming
Computer programs are instructions for getting a computer to perform a task, such as these:
- Send a text message
- Play a game
- Manage a calendar
- Drive a car
- Fly a spacecraft
Types of Computers
Programs run on computers of different sizes and types:
- mainframes
- desktops
- laptops
- tablets
- smartphones
- Arduino and Raspberry Pi
Languages
Programs are written using programming languages. Some popular ones are:
- Java
- JavaScript
- C++
- Python
- Scala
Building on the Work of Others
Programmers build on the work of other programmers. If we all had to figure out how to make 3D graphics or simulate physical processes (bouncing objects, collisions, gravity, etc.), it would take much longer to create our applications. People who are good at specific areas of programming (graphics, physics, music, etc.) publish their programs for use by others, as packages, libraries, or frameworks. p5.js, for example is a framework created by UCLA Assistant Professor Lauren McCarthy to make it easier for other programmers to make graphics, sound and art.
Some Example Programs for Inspiration
Try running some of my favorite p5.js creations, to get ideas and inspiration:
- 3D Snake Game
- 3D Elevator Simulator
- Harmonic Explorer
- Conway’s Game of Life (a 3D rendering of the 2D game)
- Cube of Cubes
- Cube to Sphere
- 3D Clock (change view in CodePen so code is on the left side)
- Arpeggio Maker
- Metronome
- Talking Name Picker
Let’s Get Coding
A Simple Program
Let’s create a p5.js program, using editor.p5js.org.
Push Play
to see what the program does. It should draw a rectangle.
Change that program to look like the following, and then run it.
function setup() {
createCanvas(400, 400)
background(0)
}
function draw() {
stroke(0, 255, 0)
line(width / 2, height / 2, mouseX, mouseY)
}
Unlike with block-based environments like Scratch, in JavaScript
you can make simple
mistakes that prevent the program from even starting. Pay careful
attention to things like parentheses ( )
, braces { }
, commas,
and where capital letters are used.
Move the mouse over the rectangle and see what happens.
Think about what width
, height
, mouseX
and mouseY
mean. What about the three numbers following stroke
?
Explanation of the Program
- the two-dimensional coordinate system
- x coordinates indicate the distance in pixels from the left side of the canvas
- y coordinates indicate the distance in pixels from the top of the canvas
- the origin is at the top left, in 2D, and in the center in 3D
- the red, green, blue (RGB) color model
- our eyes are sensitive to these three colors
- often we use numbers from 0 to 255 to specify how much of each color we want
- the setup and draw functions
- setup is called once at the beginning, and usually creates the canvas
- draw is called repeatedly and rapidly
- background
- fills the entire canvas with the specified color
- fill, stroke
- fill is the interior, and stroke is the outline
- mouseX, mouseY
- where the mouse is
- line
- a function that creates a line, given two pairs of (x, y) coordinates—one for each end
Saving Your Work
If you log in (with Google may be best), you can save your work with File -> Save.
Challenge 1, Lines from Corners
Change the program so that instead of drawing one green line from the center to the mouse position, it draws two or more lines in different colors from corners.
Solution to Challenge 1
I’ll code this for you in class. How many of you completed it?
Drawing Shapes
Let’s draw a few shapes. In order to position them on the canvas, we
give x and y coordinates. Remember that x is the distance from the left
side, and y is the distance from the top. p5.js lets us use width
and
height
to get the canvas dimensions. We can position shapes using
fractions of these dimensions. For example, width / 2, height / 2
gives
us the coordinates of the center of the canvas. width * 0.25
would give
us an x coordinate for 1/4 of the way across from the left edge.
I’ll show you some examples now.
In the p5.js reference, you can learn how to make other 2D “primitives” besides lines, such as triangles, rectangles, and ellipses.
Challenge 2, Face Program
Start with this program. Modify it so it looks like this:
What you have to understand in order to do this challenge:
- rectMode(CENTER) changes things so that when drawing rectangles, you give the location of its center and not of the top left corner
- strokeWeight(…) sets the thickness of the stroke
- you can use names for colors. Notice that I changed some colors.
- since there are two rectangles, you’ll need to duplicate the line of code that makes the one rectangle, and change something in the new line. Shall I show you how to duplicate a line?
- for the point, you’ll duplicate it twice so you’ll have three points
Solution
Here is the actual program I used to make the drawing with two “eyes”. It’s shorter than the code I made in the video.
Bonus Problem
Make your own, original creation.
Randomness
Star Field
Here’s a pretty cool star field 3D program. It’s complicated, so let’s make a simpler, 2D one together, and maybe come back to this one when you’re more experienced.
Random Points?
Here’s another program with random points. Run it and see what it makes. Can you figure out how it works? We may return to this program later, too.
Simple Star Field
Let’s make a simple 2D star field together. What you’ll learn:
- There’s a feature of p5.js called the random function that lets us randomly create x, y coordinate pairs and colors
- We can store colors we want to use in a data structure known as an array, and choose from those colors randomly
Steps in making a star field program:
- Create an array of the star colors
- Set the background to black, in the setup function
- In draw, randomly pick x and y coordinates and a color, and draw a point in that color
Challenge 3, Random Shapes
Make a program that makes shapes (rectangles, ellipses, triangles or lines) appear on the canvas. Choose one or more of the following randomly:
- Position
- Size and shape
- Color (stroke or fill)
- Stroke weight
Need a tip to get started? Modify the simple Star Field program and use rect instead of point.
Show and Tell
We’ll show some of your programs to the class towards the end of the period.
A Solution
Constants and Variables
Computer programs often need to keep track of things:
- How much an object is currently rotated
- The current color of an object
- When a student will be allowed to send their next chat message (flood control)
- A game score
- The name of the player
- Where on the game map a player is located
- What the player is carrying (inventory)
Some of these things—a score, for example—are numbers. Others that contain words or symbols, such as a name, are strings. A location in a 2D or 3D world might contain a group of two or three numbers, (x, y) or (x, y, z) coordinates, or latitude, longitude and elevation. An inventory is a collection of zero or more items, the items being strings or some other type. A common collection type in JavaScript is the array.
When you play a computer game and you save the game (or it saves itself automatically), it writes the values of the variables that track where you are in the game from random access memory (RAM) onto more permanent storage—a solid state drive (SSD) or a hard disk drive (HDD). (What’s the difference?)
Let’s play with some variables in a web site that lets us visualize running a program.
3D Graphics
It’s time now to leave the flat world of the (x, y) plane and enter the (x, y, z) three-dimensional space!
The Origin and the Axes
The origin is now in the center of the screen. x is still the horizontal position, and y is still the vertical position. z is the distance away from you, with larger numbers meaning closer to you.
A Rotating Box
I’ll show you a sketch with a rotating box.
mouseX
controls the rotation speed, and mouseY
controls the color.
A Rotating Box, from Scratch
Let’s create a rotating box program, from scratch. Make it with me.
Other 3D Shapes
Let’s look in the reference for how to make other 3D shapes.
Placing Shapes in Different Positions
Unless you request otherwise, shapes you place will appear ot the origin (the center).
Translate
You can move objects on any of the three axes, by
calling translate
. You give translate three numbers:
the amounts you want to move on each of the three
axes. These numbers can be positive or negative.
Push and Pop
If you place multiple objects in the scene, using
translate for each, the translations will interfere
with each other. So we isolate the translations by
surrounding the drawing we do with them with calls
to push
and pop
. push
saves the current
transformation state (what things like translate
and the rotation functions) do, and pop
restores
the state to how it was before the push
.
Simple Example
This program draws a cube and a cone, using push, translate, and pop.
Cooler Example
This cooler program has four objects, and they all rotate together around the y axis.
Challenge 4, Multiple 3D Shapes Artistic Sketch
Combine two or more shapes (a cylinder and a cube, perhaps). Be creative and artistic in your choice of colors, sizes and shapes.
If you like, have it rotate. You might control various aspects
of it with mouseX
and mouseY
, as I did.
Multiple 3D Objects Using Loops
When placing multiple similar objects in your scene in a regular pattern, you needn’t repeat blocks of code. You can use loops.
Complicated Example
This example makes a field of objects. It uses a loop within a loop. This is meant to show you the power of loops, but let’s not study it just yet.
Simpler Example
This simpler example uses a single loop to make three objects. Let’s study it.
Challenge 5, Multiple 3D Shapes Using One or More Loops
Make a program that creates multiple objects using one or more loops. You can use one of the above programs as a starting point if you like.
Bonus challenge: use a loop within a loop within a loop to translate on x, y, and z.
Sound
p5.js has a feature that lets us make sounds.
Oscillator
An oscillator creates a tone at a specific frequency. This code makes a tone at the frequency 440 hz.
Run this “440 Oscillator” program
You can change the 440 to different numbers to hear different frequencies.
Controlling Frequency with mouseX
You can change the frequency when the mouse moves.
Mouse frequency example program
Pitch Matching Game
Here is a very cool pitch matching game, using two oscillators.
Tuning and “Beats”
Challenge 6: Do Something Creative with Sound
Use what you’ve learned about p5.Oscillator to make something creative and interesting. Here is an example.
Playing Notes Using MIDI Note Numbers
Let’s study this Multi-Octave Spooky Music program and make spooky Halloween music.
Keyboard Input
You can use the keyboard in your programs. Here’s a program where you move a square to the right with an arrow key.
When you run the program, click on your canvas before pressing keys so the keyboard input will be directed to the program.
Problems
- Move all four directions using all four arrow keys
- (Advanced) Make the program 3D and move on x and y
- (Advanced) Make the program 3D and move on x, y and z using the four arrow keys plus w and s