The template code contains two blocks, or functions, setup() and draw(). You can put code in either place, and there is specific purpose for each. Any code involved in setting up the initial state of your program goes in the setup() block. Any code involved in actually drawing to the screen (setting the background color, or drawing shapes, text, or images) will be placed in the draw() block.

function setup() {
	// put setup code here
}
 
function draw() {
	// put drawing code here
}

The code within the draw() block runs from top to bottom, then repeats until you quit the program by closing the window. Each trip through draw() is called a frame. The default frame rate is 60 frames per second. To complement the looping draw() function, p5.js has the setup() function that runs just once when the program starts. You can place global variables outside of setup() and draw(). This is clearer when we list the order in which the code is run.

Fundamentals

createCanvas (width, height)

  • Creates a canvas element on the web page. It should only be called once at the beginning of setup(). Calling more than once causes unexpected behavior.
  • Typical use: createCanvas(windowWidth, windowHeight)

background (colorstring), (grayscale, [alpha]), (r,g,b)

  • Sets the color used for the background of the canvas. By default, the background is transparent. background() is typically used within draw() to clear the display window at the beginning of each frame. It can also be used inside setup() to set the background on the first frame of the animation.

Basic shapes

When a program runs, the computer starts at the top and reads each line of code until it reaches the last line and then stops. If you want a shape to be drawn on top of all other shapes, it needs to follow the others in the code.

  1. point(x, y)

  2. line(x1, y1, x2, y2)

  3. circle(x, y, d)

  4. ellipse(x, y, w, h)

  5. triangle(x1, y1, x2, y2, x3, y3)

  6. square(x, y, s)

  7. rect(x, y, w, h)

  8. quad(x1, y1, x2, y2, x3, y3, x4, y4)

Properties:

strokeWeight(weight)

  • sets the width of the stroke used for points, lines, and the outlines of shapes. It is affected by transformations, especially calls to scale().

strokeJoin(join)

  • Sets the style of the joins that connect the line segments. Joins are either MITER, BEVEL or ROUND.

stroke (grayscale, [alpha]), (r,g,b)

  • Sets the color used to draw points, lines, and the outlines of shapes.

fill (grayscale, [alpha]), (r,g,b)

  • Sets the color used to fill shapes.

noSroke()

  • Disables drawing points, lines, and outlines of shapes.

Programming constructs

vars, for loops, if statements, functions, objects, arrays

A series of special variables to store information about the program while it runs.

width: A Number variable that stores width of the canvas in pixels. Initialized only after setup() is called.

height:

mouseX: A Number system variable that tracks the mouse’s horizontal position.

mouseY:

pmouseX: A Number system variable that tracks the mouse’s previous horizontal position.

pmouseY:

mouseIsPressed: A Boolean system variable that’s true if the mouse is pressed.

mouseButton: A String system variable that contains the last mouse button pressed.

keyIsPressed: A Boolean system variable that’s true if any key is currently pressed.

key: A String system variable that contains the value of the last key typed.

Math

PI:

dist(x1, y1, x2, y2): Calculates the distance between two points.

map(value, start1, stop1, start2, stop2): Re-maps a number from a range to another.

Mouse ideas

Dot follows you:

function draw() {
	ellipse(mouseX, mouseY, 10, 10);
}

Draw smoothly:

function draw() {
	line(pmouseX, pmouseY, mouseX, mouseY);
}

Set thickness on the fly:

function draw() {
	var weight = dist(mouseX, mouseY, pmouseX, pmouseY);
	strokeWeight(weight);
	line(mouseX, mouseY, pmouseX, pmouseY);
}

Easing:

let x = 0;
let y = 0;
let px = 0;
let py = 0;
let easing = 0.5;
function draw() {
	x += (mouseX - x) * easing;
	y += (mouseY - y) * easing;
	let weight = dist(x, y, px, py);
	strokeWeight(weight);
	line(x, y, px, py);
	px = x;
	py = y;
}

Transformations

An alternative techniques for positioning and moving things on screen is to change the screen coordinate system. Note: transformations are reset at the beginning of the draw loop Calling translate inside the draw() function won’t cause shapes to move continuously.

`translate(x, y)

  • Translates the coordinate system. By default, the origin (0,0) is at the sketch’s top-left corner in 2D mode.

rotate(angle)

  • Rotates the coordinate system. By default, the positive x-axis points to the right and the positive y-axis points downward.

scale(scales)

  • Scales the coordinate system. By default, shapes are drawn at their original scale. Note: To keep consistent stroke weight as a shape scales, divide the desired stroke weight by the scalar value.

push() and pop()

  • Begins a drawing group that contains its own styles and transformations. By default, styles and transformations are applied to all drawing that follows. These functions can limit the effect of styles to a specific group of shapes.

Media

A new function called preload() loads assets before the sketch runs. You should generally load your images and other media here to ensure that they are fully loaded before your program starts.

loadImage(path)

  • Loads an image to create p5 object.

image(img, x, y, [width], [height])

  • Draws an image to the canvas.

Why not use setup()? We’ve been assuming that our program runs from top to bottom, with each line completing before going on to the next one. Although this is generally true, when it comes to certain function like loading images, your browser will begin the process of loading the image, but skip onto the next line before the image finishes loading. This is known as asynchronicity. It’s a little bit unexpected at first, but this ultimately allows your pages to load and run faster on the Web.

pixels:

  • An array containing the color of each pixel on the canvas. Some displays use several smaller pixels to set the color at a single point. The pixelDensity() returns the pixel density of the canvas.

loadPixels()

  • Loads the current value of each pixel on the canvas into the pixels array.

updatePixels()

  • Updates the canvas with the RGBA values in the pixels array.

Motion

To create smooth motion, p5.js tries to run the code insider draw() at 60 frames each second. A frame is one trip through the draw() function and the frame rate is how many frames are drawn each second. Therefore, a program that draws 60 frames each second means the program runs the entire code insider draw() 60 times each second.

  1. Move a shape
function draw() {
	background(0);
	x += speed * direction
	if ((x > width-radius) || (x < radius)) 
	{
		direction *= -1
	}
	if (direction == 1) 
	{
	    arc(x, 60, radius, radius, 0.52, 5.76);
	} 
	else 
	{
	    arc(x, 60, radius, radius, 3.67, 8.9);
	}
}
  1. Tweening
var startX = 20;
var stopX = 360;
var startY = 30;
var stopY = 400;
var x = startX;
var y = startY;
var step = 0.05;
var pct = 0.0;
 
function draw() {
	background(0);
	if (pct < 1.0) 
	{
		x = startX + ((stopX - startX) * pct);
		y = startY + ((stopY - startY) * pct);
		pct += step;
	}
	ellipse(x, y, 20, 20);
}
  1. Utility Functions

    • millis(): Returns the number of milliseconds since a sketch started running.
    • random([min], [max]): Returns a random number or a random element from an array.