Note for Class

  1. Punctuation in p5.js

Parentheses (): Used to pass inputs (arguments) into a function.

Semicolon ;: Marks the end of a code statement (like a period in a sentence).

  1. Variable Scope (setup vs. draw)

Declared at the top outside functions:

Written before setup().Every function (setup and draw) can use/ update this variable.

Declared inside {}:

Only works inside that specific block {}.

Resets every time the loop runs.(If in draw)

Why put let x at the top?

If let x = 50 is at the top, and set x = width inside setup(), x becomes width when the program starts.

If set x = width inside draw(), x will reset every frame, and your object will not move.

  1. Math Operators & Values

Movement Shortcuts:

x = x + 7 is the same as x += 7 (moves right by 7px).

x++ is the same as x += 1 and x = x + 1 (moves right by 1px).

x -= 1 (moves left).

x *= 2 (moves right much faster).

x /= 2 (slows down and moves left toward 0).

Color Variables:

Yes, a variable can hold a color!Example: let myColor = color(255, 0, 0);

console.log(x):

Prints the value of x in the browser's developer console for debugging.

  1. Modes & Shapes

rectMode(CORNERS): Uses Top-Left $(x1, y1)$ and Bottom-Right $(x2, y2)$ coordinates to draw a rectangle.

Circles: Circles do not have a CORNERS mode because they are drawn from the center by default.

  1. Trigonometry in Programming

sin(angle) & cos(angle): Both output numbers between $-1$ and $1$.

map(sin(t), -1, 1, 0, 400): Converts the wave value ($-1$ to $1$) into canvas coordinates ($0$ to $400$) to create smooth, oscillating motion.

截圖 2026-09-16 凌晨1.42.57.png

截圖 2026-09-09 下午1.38.16.png

Video note

The Random function —

random(minimum, maximum)

The Map function — eg: map(sin(+), -1, 1, 0, 400)

map(variable, __min Current Range, __max CR, __min New Range, __max NR)

createGraphics()

Boolean — eg: if(MouseX > 10 ){fill(255, 0, 0);}

if( ____ boolean expression(true or false)){ _______ }

true or false: x > 10, x < 10, x ≥ 10, x ≤ 10, x = = 10…etc.

Homework

Worksheet 002

  1. Start with this sketch. The default p5 arguments for the rect() function are: x, y, w, h where x, y are the coordinate for the top left corner and w, h are the width and height of the rectangle. What are other ways to define a rectangle? Make up your own arguments for rect()? Come up with at least 2 sets.
  2. Draw a rectangle in the middle of the screen that is half the width and half the height of the canvas. Write it so that you can change the size of the canvas and the rectangle will stay in the center and maintain its size relationship to the canvas.
  3. Re-draw the rectangle using line(). Challenge: Write it so that you can easily change the location and size relationship with the canvas.