How to create colored particles effect using p5js. EASY!
Tags: javascript, p5js, particles, animation
Published: 2022-01-28 06:31:54

For my very **first** DEV.to post, I am here with something exciting that I made a couple of days back. **COLORED PARTICLES**! 🥳

✨ Yes! Particle effect is an interesting animation. Tiny balls and their connecting lines gives a very beautiful visual experience and it has many use cases as well.

🤩Here's a sneak peek of what we are going to build:

{% codepen https://codepen.io/bitnagar/pen/mdBoXOr height=520 ,result %}

We will dive deep into creating this effect. Without wasting time, let's go!

This blog is divided into two sections, **"Getting Started"** and **"Code it out!"**. We will first do the initial setup of our editor and then we will code it out.

> **Note**: This blog assumes that you know basics of **P5.js** along with **OOPS** concepts.

---

## ⚜️ Getting Started ⚡
Let's first set our IDEs or editors in order to create particles:
 
**Step 1:** Create and set your HTML CSS and JS files with basic boiler plate code.
**Step 2:** Inside HTML file, add the following script to include [p5js library.](https://p5js.org/get-started/#:~:text=Using%20a%20hosted%20version%20of%20the%20p5.js%20library)

```
https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js;
```
**Step 3:** Reset default padding and margins in CSS files. You know the drill. 😛
**Step 4:** You're done with initial setup :P

---

## 🔱 Code it out! 😈
For this, we are going to work in JavaScript file.

Let me give you an overview of what we are essentially going to do in our code.
 
1. Creating an array to store particles.
2. Creating a **class** for particles.
3. Setting up our ***setup( )*** function.
4. Setting up our ***draw( )*** function.

Let's do all of these one by one.🔥

**1.** Create an array. We will **push** particles into this array later.

```javascript
const particles = [];
```
---

**2.** Create a **class** for particles:
> This class will contain:
> 1. a constructor for instantiating a **Particle( )** object.
> 2. methods for particle functionality. (movement, bouncing back etc).

[`constructor`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) method is a special method for creating and initializing an object instance of that class.

```javascript
class Particle {
     constructor() { /* code here */ }
}
```

🔹This constructor will contain properties that will exist in a particle.

🔸We want our particle to move on the X-Y axis and if our particle is moving, that means it must have a `velocity`. 
A particle would also have a `size` or radius, because it is basically a circle.

🔹SO, the 3 properties are going to be:

- `pos` = position of the particle,
- `vel` = velocity of the particle and,
- `size` = radius of the particle.

```javascript
    constructor() {
        //POSITION
        this.pos = createVector(random(width), random(height));
        //VELOCITY
        this.vel = createVector(random(-1, 1), random(-1, 1));
        //SIZE
        this.size = 10;
    }
```

[`createVector`](https://p5js.org/reference/#/p5/createVector) creates a `vector` on the given X and Y co-ordinates. A vector is an entity that has both _magnitude_ and _direction._

🔸We have given random X-Y values to the `createVector()` of `pos` because we want our particles to appear on random places on the screen. For this we use p5.js built in method `random()`.

🔹We'll assign the `vel` property a vector with random values ranging from -1 to 1 because we will add this vector, or we will add three values -1, 0, 1 to the X and Y co-ordinate of `pos` in order to change the position of particle when our frame updates.

You can give any `size` to your particle (keep it small🤭).

🔸To give some random color to particles and lines, we'll assign random values ranging from `0 to 255` to `r, g, b` variables. `constructor()` will look like this in the end.

```javascript
constructor() {
     //POSITION
     this.pos = createVector(random(width), random(height));
     //VELOCITY
     this.vel = createVector(random(-1, 1), random(-1, 1));
     //SIZE
     this.size = 10;

     this.r = random(0, 255);
     this.g = random(0, 255);
     this.b = random(0, 255);
}
```

🔹Now, for updating the movement of particle in every call of 
  `draw()` function, we will create an `update` method inside 
  **Particle** class.

🔸`function update()` will add velocity vector into position vector, plus it will call another function called `edges()` for collision detection. We will create it in a bit. Keep on reading!

```javascript
update(){
        this.pos.add(this.vel);
        this.edges();
    }
```

🔹We have given given properties to our particles, but we are still not drawing them on canvas. Let's create a function inside Particles class for drawing particles.

```javascript
drawParticle() {
        noStroke();
        fill(this.r,this.g, this.b)
        circle(this.pos.x, this.pos.y, this.size);
    }
```

🔸For detecting the edges of the canvas, we will create a function called `edges()`. 

> **Logic behind** `function edges()` :
> 
> if `X` or `Y` `position` of the particle is less than `< 0` OR `X` or `Y` `position` of particle is less than `< width` or `< height` of `canvas` respectively, then `multiply -1` with `velocity X or Y` vector respectively.

```javascript
 edges() {
    
        if(this.pos.x < 0 || this.pos.x > width) {
            this.vel.x *= -1;
        }
        if(this.pos.y < 0 || this.pos.y > height) {
            this.vel.y *= -1;
        }
    }
```

🔹Connecting particles with lines:
`checkParticles()` will check if particles are in a certain distance from each other, if true, it will draw a `line` between them.(I call them webs 🕸️🕷️)

```javascript
  checkParticles(particles) {
        particles.forEach(particle => {
            const d = dist(this.pos.x, this.pos.y, particle.pos.x, particle.pos.y);
            if (d < 120) {
                stroke(this.r,this.g, this.b);
                line(this.pos.x, this.pos.y, particle.pos.x, particle.pos.y)
            }
        });
    };
```

🔸`stroke()` will color the lines in a random color, every time the page reloads.

> **Note:** The next step is optional!

✨Creating a hover effect on particles. Consider it as a bonus. 🤭

🔹`repel()` function will make particles move away from the mouse cursor, creating a hover effect.

```javascript
 repel() {
        this.pos.x = constrain(this.pos.x, 0, width);
        this.pos.y = constrain(this.pos.y, 0, height);
        let distance = dist(this.pos.x, this.pos.y, mouseX, mouseY);
        let mouse = createVector(mouseX, mouseY);
        let difference = p5.Vector.sub(mouse, this.pos);
        difference.setMag(1);
        //If the mouse comes near a particle, it moves away
        if (distance < 400) {
          this.pos.sub(difference);
        }
      }
}
```

😈 As this method is optional, I am going it to leave it unexplained. Go ahead, try to figure out what is happening in above function. 😁

🎉 So we have successfully created our `Particle` class. Now we will create `setup()` function.

---


**3.** Setting up our **setup( )** function:
🔸Create a canvas of size same as window width and height. 

```javascript
function setup() {
	createCanvas(window.innerWidth, window.innerHeight);
}
```

🔹 Create a **const** (name it whatever you want) for storing a value for number of particles. We want the number of particles to be **proportional** to the **window width.**

```javascript
function setup() {
      createCanvas(window.innerWidth, window.innerHeight);
      const particlesLength = Math.floor(window.innerWidth / 9);
}
```

🔸 Create a `for` loop to push a **Particle( )** (which we will get from **Particle class**) into the array we created earlier.
	   

```javascript
 function setup() {				    
      createCanvas(window.innerWidth, window.innerHeight);
      const particlesLength = Math.floor(window.innerWidth / 9);
      for (let i = 0; i < particlesLength; i++) {
	  particles.push(new Particle());     
      }
 }
```

**That's it for the setup function! 🥳**

---


**4:** Setting up our ***draw( )*** function:

🔹We will take the particles array and for each particle inside array, we will run all the methods that we have created in the Particle class in order to give them all the functionality.  

```javascript
 function draw() {
	    background(0);
	    particles.forEach((p, index) => {
	        p.update();
	        p.drawParticle();
	        p.checkParticles(particles.slice(index));
	        p.repel();
	    })
	}
```

🔸We will keep `background()` set at `0` so that canvas repaints every time the `draw()` function executes.

😎Finally, we're done with code, run your program in your system and boom! PARTICLES EVERYWHERE!!🤩

Check the final JS code and live demo here. 👇🏻

{% codepen https://codepen.io/bitnagar/pen/preview/mdBoXOr height=520 default-tab=js,result %}

🎉🎉🎉**Congratulations** 🥳, for making this far. You did it, and hopefully created some tiny particles effect using p5js.✨✨✨

I hope enjoyed and learned something new from this blog.💯.

Comment your thoughts about it💭. Give feedback 📝 and share it with your friends 🌏. See you in the next blog.🙋🏻‍♂️

Twitter: [@bitnagar](https://twitter.com/bitnagar)