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:
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://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.
- Creating an array to store particles.
- Creating a class for particles.
- Setting up our setup( ) function.
- 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.
const particles = [];
2. Create a class for particles:
This class will contain:
- a constructor for instantiating a Particle( ) object.
- methods for particle functionality. (movement, bouncing back etc).
constructor
method is a special method for creating and initializing an object instance of that class.
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.
constructor() {
//POSITION
this.pos = createVector(random(width), random(height));
//VELOCITY
this.vel = createVector(random(-1, 1), random(-1, 1));
//SIZE
this.size = 10;
}
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.
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!
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.
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
orY
position
of the particle is less than< 0
ORX
orY
position
of particle is less than< width
or< height
ofcanvas
respectively, thenmultiply -1
withvelocity X or Y
vector respectively.
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 🕸️🕷️)
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.
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.
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.
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.
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.
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. 👇🏻
🎉🎉🎉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
Top comments (0)