JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="500" height="500"></canvas>
JavaScript
//Lets create a simple particle system in HTML5 canvas and JS
//Initializing the canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Canvas dimensions
var W = 500;
var H = 500;
//Lets create an array of particles
var particles = [];
for (var i = 0; i < 500; i++) {
//This will add 50 particles to the array with random positions
particles.push(new create_particle());
}
//Lets create a function which will help us to create multiple particles
function create_particle() {
//Random position on the canvas
this.x = Math.random() * W;
this.y = Math.random() * H;
//Lets add random velocity to each particle
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 - 1;
//Random colors
var r = 0 >> 0;
var g = 0 >> 0;
var b = 255 >> 0;
this.color = "rgba(" + r + ", " + g + ", " + b + ", 0.2)";
//Random size
this.radius = 10;
}
var x = 100;
var y = 100;
//Lets animate the particle
function draw() {
ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
ctx.fillRect(0, 0, W, H);
//Lets draw particles from the array now
for (var t = 0; t < particles.length; t++) {
var p = particles[t];
ctx.beginPath();
//Time for some colors
var gradient = ctx.createRadialGradient(p.x, p.y, 1, p.x, p.y, p.radius);
gradient.addColorStop(0, "white");
gradient.addColorStop(0.1, "blue");
gradient.addColorStop(0.6, p.color);
gradient.addColorStop(1, "black");
ctx.fillStyle = gradient;
ctx.arc(p.x, p.y, p.radius, 5 * 2, true);
ctx.fill();
//Lets use the velocity now
p.x += p.vx;
p.y += p.vy;
}
}
setInterval(draw, 33);
//I hope that you enjoyed the tutorial :)