FRI | Classes

FRI | Classes


Inspiration #


Classes in JavaScript #

Classes in JavaScript are not objects.
They are templates for creating objects.

Classes are kind of like cookie cutters that you can use to create multiple cookies (objects).

See the JS Classes tutorial.

This way of using classes is very similar to how they work in Processing and many other programming languages. Therefore, I will generally use classes to create objects during this course. This will help you work with other programming languages that you might use during your studies.

The minimum structure for a class is like this. You come up with a name for your class, and you write the constructor() method.

class ClassName {
  constructor() {
  }
}

A simple class called Dog could look like this.

class Dog {
  constructor() {
    this.name = "Kimchi";
    this.breed = "Husky";
    this.age = 5;
  }
}

Constructor #

The constructor method is a special method:

  1. It has to have the exact name “constructor”
  2. It is executed automatically when a new object is created
  3. It is used to initialize object properties

It might be helpful to thing of the costructor as the setup of the class. Just like in our p5.js programs the constructor is excecuted automatically in the beginning when the object is created.

Classes were added into JavaScript in an update called ES6 in 2015.

Methods #

Besides the constructor method, you can create your own methods as well. You write them in the same way as the constructor.

Note that you do not need the keyword function in front of the function name. This class has two methods besides the constructor(). They are called bark() and birthday().

class Dog {
  constructor(){
    // code here
  }
  bark(){
    // code here
  }
  birthday(){
    // code here
  }
}

this #

A special keyword this is used with classes and objects. It is used to refer to the object itself. Whan you want to use some property of an object, you need to add this. before the property name.

class Dog {
  constructor(){
    this.name = "Kimchi";
    this.breed = "Husky";
    this.age = 5;
  }
  bark(){
    console.log("Bark!");
  }
  birthday(){
    console.log("Happy Birthday!");
    this.age = this.age + 1;
  }
}

Learn more about this

You will forget to use the word this with objects and classes. There is even a song about it.


Examples: Walker #

Simple Walker #

Let’s create a simple example based on something that we have done before: the random walker.

We need to create a class called Walker that is able to create Walker objects. Each walker should have the following properties:

  • x the x coordinate
  • y the y coordinate
  • s the size of the walker
  • c color
  • name a string that stores a name for the walker
  • we could add some other properties as well, but let’s keep this first example simple

Additionally, we should create the following methods for the Walker

  • constructor this one is always needed, you can initialize all the properties in the contructor
  • move a method that will move/animate the Walker, basically something that does the walk
  • draw a method that deals with drawing our Walker

The class could look like this:

class Walker {
  constructor(){
    this.x = random(width);
    this.y = random(height);
    this.s = random(10,100);
    this.c = color(random(255));
    this.name = "Matti";
  }

  move(){
    this.x = this.x + random(-3,3);
    this.y = this.y + random(-3,3);
  }

  draw(){
    fill(this.c);
    circle(this.x, this.y, this.s);
  }
}

And here is the full code:

Array of Walkers #

Once you have made the Walker class, it’s very easy to create many instances of the Walker.

Walker Explosion #

In this example, we make all the walkers emerge from the same location. This starting location is randomized when the code starts.

We also replace all the walkers in the array with new ones when the mouse is clicked. The x and y location is based on the mouse coordinates. This creates an effect that looks like the walker objects are exploding from the mouse cursor


Examples: Rain #

What is rain? Lots of individual raindrops falling down. Each drop of rain has its own size, location, speed, and behavior but all of them are essentially the same type of object. Using classes seems like the right tool if we want to create something similar to rain with our code.

Raindrop Class #

The first thing we need is a class for one individual raindrop. We should start by listing out all the properties a raindrop should probably have.

class Raindrop{
  constructor(){
    this.x; // x coordinate
    this.y; // y coordinate
    this.w; // width of the raindrop
    this.h; // height of the raindrop
    this.c; // color
  } 
}

Then we should try to come up with a visual representation of a raindrop that we can draw in p5.js. I will go for a sort of comic book look for the rain: a stretched out rectangle. I used Midjourney to try to create an example of this look.

Comic book rain

We need a draw() method for our class. The code inside the constructor randomizes the size and the position for the raindrop when it is created.

class Raindrop{
  constructor(){
    this.x = random(width);
    this.y = 200;
    this.w = random(2,4);
    this.h = random(10,30);
    this.c = color(255);
  }
  draw(){
    fill(this.c);
    noStroke();
    rect(this.x, this.y, this.w, this.h);
  }
}

Let’s see how it looks:

That seems fine for now, we can edit it later. Raindrop should also drop from somewhere. So let’s try to animate it with another method. The update() method moves the raindrop down on the y axis and checks when it goes outside of the screen. Once that happens, the raindrop gets moved to the top of the screen and to a random x location. I also changed the code so that it starts from outside of the screen. Additionally, I added a new property v for the velocity of the movement.

class Raindrop{
  constructor(){
    this.x = random(width);
    this.y = 200;
    this.w = random(2,4);
    this.h = random(10,30);
    this.c = color(255);
    this.v = random(8,16);
  }
  update(){
    this.y = this.y + this.v;
    if(this.y > height){
      this.x = random(width);
      this.y = -this.h;
      this.v = random(8,16);
    }
  }
  draw(){
    fill(this.c);
    noStroke();
    rect(this.x, this.y, this.w, this.h);
  }
}

From one drop to rain #

Now that our Raindrop class seems to work quite nicely, we can create lots of Raindrops to make it rain!

It seems ok, but the results could be improved with some fine-tuning:

  • All of the raindrops start from the same y position so the rain falls in a funny way in the beginning.
  • The speed is perhaps a bit too fast
  • Now that there are many raindrops, each drop could be made a bit smaller

More Advanced Examples #

Noise Particles #

Click & Drag Particles #

Simple Game #


Resources #


Homework: Fish Class #

These are the minimum requirements that you should try to fill for this assignment. You will notice that they are a recap of many of the different topics we have covered already in other assignments. This is on purpose for you to recap the things we have learned and also to be able to see how we can start to create more complex programs by breaking the different aspects of it into smaller and more manageable parts.

Create a class called Fish. The class should have the following methods:

  • constructor() This one needs to always be there when using JavaScript classes. Use random() for some of the variables to create a slightly different fish every time you use the class.
  • swim() This method animates the fish to move around. You can use the bouncing ball example as the way to move the fish around.
  • show() This method displays the fish. Use the 2D shapes to draw the fish.

Then make an array that uses the Fish class to draw multiple fish on the canvas.

Extra challenge #

If the basic requirements are too easy or you want to challenge yourself, consider adding some of these features:

  • interaction with the keyboard and/or mouse
  • sound effects
  • interaction with the sound input
  • more complex animation for the fish (rotations, randomness etc.)
  • Use layers of .png images as the fish and animate them like a cut-out animation
  • Import a 3D object as the fish
  • Anything else you can think of!