
Last Updated on March 15, 2025 by E. Scott
In this blog post, we’ll dive deep into creating a JavaScript canvas particle system using the HTML5 canvas element and JavaScript. This system will generate particles that move around the screen, change colors, and scale based on their position in a 3D space.
The canvas element is an HTML tag that provides a drawing surface for JavaScript. It is a powerful tool for rendering graphics, animations, and interactive content. The canvas element itself does not have any drawing capabilities; it acts as a container for the drawing context, which is accessed via JavaScript.
Make no mistake though, JavaScript canvas animations are very complex. More so than other tasks in JavaScript in my opinion. We’ll create two versions here.
Table of Contents
Preparing the JavaScript Canvas
Particle animations can add a touch of elegance and interactivity to any web page. This animation will feature a dynamic background with moving particles that change color and position over time.
Add the canvas element to the HTML:
<canvas id="particleCanvas"></canvas>
Initialize the JavaScript:
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
- The above code, retrieves the canvas element from the DOM.
- Gets the 2D rendering context of the canvas, which provides methods and properties for drawing on the canvas.
- Sets the canvas dimensions to the full width and height of the viewport.

Creating the Particle Class
We’ll define a Particle class to represent each particle in the system. Each particle will have properties like position (x, y, z), size, speed, and color. The class will also include methods to update the particle’s position and draw it on the canvas. Something to note here is that all modern frontend frameworks use classes which are often times thought of as components. But classes are used for all types of things, such as this JavaScript canvas animation!
class Particle {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.speedZ = Math.random() * 3 - 1.5;
this.color = this.getRandomColor();
}
getRandomColor() {
const colors = ['#0080ff', '#007acc', '#f7df1e', '#1e1e1e'];
return colors[Math.floor(Math.random() * colors.length)];
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.z += this.speedZ;
if (this.x > canvas.width || this.x < 0) {
this.x = Math.random() * canvas.width;
}
if (this.y > canvas.height || this.y < 0) {
this.y = Math.random() * canvas.height;
}
if (this.z > 1000 || this.z < -1000) {
this.z = Math.random() * 2000 - 1000;
}
}
draw() {
const scale = 1 / (1 + Math.abs(this.z) / 500);
const scaledSize = this.size * scale;
const scaledX = (this.x - canvas.width / 2) * scale + canvas.width / 2;
const scaledY = (this.y - canvas.height / 2) * scale + canvas.height / 2;
if (scaledSize > 0.5) {
ctx.beginPath();
ctx.arc(scaledX, scaledY, scaledSize, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
}
- The constructor initializes the particle properties.
- x, y, z initializes the position in 3D space.
- Size is a random value between 1 and 6.
- speedX, speedY, and speedZ are random speeds in each direction.
- Color is a randomized value from a predefined array.
- getRandomColor returns a random color from the colors array.
- update: Updates the particle’s position based on its speed. If the particle goes out of bounds, it is reset to a random position.
- draw: Draws the particle on the JavaScript canvas. The particle’s size and position are scaled based on its z position to simulate a 3D effect.
const particlesArray = [];
function createParticles() {
for (let i = 0; i < 500; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const z = Math.random() * 2000 - 1000;
particlesArray.push(new Particle(x, y, z));
}
}
- Loop: Creates 500 particles.
- Random Position: Each particle’s initial position (x, y, z) is randomly generated within the JavaScript canvas dimensions and a 3D space.
- Push to Array: Adds each new particle to the particlesArray.
Handling the Animation
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particlesArray.length; i++) {
particlesArray[i].update();
particlesArray[i].draw();
}
requestAnimationFrame(animate);
}
- Clear Canvas: Clears the entire canvas to prepare for the next frame.
- Update and Draw: Iterates through each particle, updates its position, and draws it on the canvas.
- Request Animation Frame: Recursively calls the animate function to create a smooth animation loop.
Handling Window Resize Events
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
particlesArray.length = 0;
createParticles();
});
- Resize Event:
- Listens for the window resize event.
- Adjusts the canvas dimensions to the new viewport size.
- Clears the existing particles array and creates new particles to fit the resized canvas.
- Below, initialize the particles and begin the animation.
createParticles();
animate();
JavaScript Canvas Animation Version 2
First, let’s set up the basic HTML structure. We’ll need a canvas element to draw our particles.
<canvas id="particleCanvas"></canvas>
This next script is very close to the one previously explained. Each JavaScript canvas animation takes tremendous processing power so I created this one with the hopes of limiting thereof. The first one makes my laptops fan run incessantly while this version is an improvement. Both however work without a hitch on mobile. Regardless, check it out. Let me know what you think in the comments below.
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Particle class
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 3 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.color = this.getRandomColor();
}
getRandomColor() {
const colors = ['#0080ff', '#007acc', '#f7df1e', '#1e1e1e'];
return colors[Math.floor(Math.random() * colors.length)];
}
update() {
this.x += this.speedX;
this.y += this.speedY;
// Reset particle if it goes off screen
if (this.x > canvas.width || this.x < 0) {
this.x = Math.random() * canvas.width;
}
if (this.y > canvas.height || this.y < 0) {
this.y = Math.random() * canvas.height;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
// Array to hold particles
const particlesArray = [];
// Function to create particles
function createParticles() {
for (let i = 0; i < 100; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
particlesArray.push(new Particle(x, y));
}
}
// Function to handle animation
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particlesArray.length; i++) {
particlesArray[i].update();
particlesArray[i].draw();
}
requestAnimationFrame(animate);
}
// Event listeners for resizing the canvas
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
particlesArray.length = 0;
createParticles();
});
// Initialize particles and start animation
createParticles();
animate();
// Start text animation
animateText();
If you’re new to web development, I’d suggest learning the fundamentals first. JavaScript canvas animations are considered fairly advanced. In turn, learn and practice HTML first. Then of course master CSS.
In this blog post, we explored how to create a dynamic particle system using a native HTML5 tag to create a JavaScript canvas animation. We defined a Particle class to manage individual particles, created an array to store and manage multiple particles, and set up an animation loop to continuously update and render the particles. This project demonstrates the power and flexibility of the canvas element and JavaScript for creating engaging and interactive web content. Whether you’re a beginner or an experienced developer, experimenting with canvas animations can open up a world of creative possibilities.
Leave a Reply