This is a primer on how to code in JavaScript with p5.js. We’ll be going through the basics of what variables and functions are, and how to use them. p5.js is a JavaScript library for creative coding, and is a great place to start learning as it allows you to see visually what the code you’re writing actually does; the cause and effect is really effective.

We’ll start by drawing an emoji made out of basic shapes, improving and making our code cleaner and more efficient as we go, and finally we’ll make the emoji animate and really emote.

Contents

  1. What is code?
  2. What is p5.js?
  3. Drawing shapes
  4. Cleaner code
  5. Useful logic
  6. Animating shapes
  7. Classes

What is code?

Code is like any other language, composed of grammar and syntax.

<aside> <img src="/icons/arrow-right_purple.svg" alt="/icons/arrow-right_purple.svg" width="40px" /> code = grammar + syntax

</aside>

Grammar

Variables are the nouns of code, they’re like boxes that store values. They can store numbers and strings (words), and their contents can be changed at any time.

Functions are the verbs of code, they’re the doing part. You can use a function to draw an ellipse or change the fill colour.

You can combine variables and functions to do verbs with nouns. So for example, draw an ellipse of size 10x10 pixels in the middle of a canvas.

<aside> <img src="/icons/arrow-right_purple.svg" alt="/icons/arrow-right_purple.svg" width="40px" /> nouns = variables

</aside>

width
height
xPosition
yPosition
radius
size

<aside> <img src="/icons/arrow-right_purple.svg" alt="/icons/arrow-right_purple.svg" width="40px" /> verbs = functions

</aside>

createCanvas()
background()
fill()
rect()
ellipse()
random()