Tried Implementing Background Animation with p5.js
I implemented background animation using p5.js to bring movement to my static portfolio site. I will look back from a beginner's perspective, from introduction to implementation of 10 patterns.
Hello! I'm PanKUN.
I decided to try using p5.js, which is famous in the world of creative coding.
What is p5.js?
It is a library that makes Processing, a programming language for art, work on the Web (JavaScript). Things like "drawing pictures on a canvas" and "moving them" can be written with surprisingly simple code.
Introduction is Super Easy
There is also a method to install with npm, but this time I introduced it easily with CDN. Just add one line to HTML.
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>Preparation is complete with just this.
Let's Write Immediately
First, I started from "creating a canvas on the entire screen and displaying a circle".
function setup() {
// Create a canvas full of screen
createCanvas(windowWidth, windowHeight);
}
function draw() {
// Clear background
clear();
// Draw a circle (x, y, size)
circle(100, 100, 50);
}I was able to draw with just this.
It is a mechanism where setup() is called only once at the beginning, and draw() is called every frame.
Trying to Fly Particles
If you classify the circle, put it in an array, and update the coordinates, it becomes an animation where countless particles move.
class Particle {
constructor() {
this.x = random(width);
this.y = random(height);
}
update() {
this.y -= 1; // Rise up
}
display() {
circle(this.x, this.y, 5);
}
}If you loop this inside draw(), the animation rising like bubbles is complete.
If you use vectors and trigonometric functions, you can also create more complex movements.
Got Carried Away and Created 10 Patterns
It became fun, so I implemented various patterns.
- Network: Connect particles with lines (Neural network style)
- Cosmos: Stars twinkling
- Rain: Digital rain (Matrix style)
- Circuit: Pulses running like a circuit diagram
...and so on, a total of 10 types!
I made it switch randomly every time the page is opened, so you can enjoy a different atmosphere every time you reload.
Trap of Smartphone Measures
One thing I got stuck on during implementation was occurrence of horizontal scrolling on smartphones.
If you write
createCanvas(windowWidth, windowHeight)
it is no problem on PC, but on smartphones, the width of the scroll bar is included, and sometimes it slightly exceeds the screen width.
Finally,
let w = document.documentElement.clientWidth;I solved it by getting the accurate width excluding the scroll bar like this.
Summary
I touched p5.js for the first time, but the experience of "drawing pictures with code" was very fresh and fun.
Why don't you add "a little playfulness" to your site too?
Loading comments...