JSFiddle - React, Tailwind, and code Playground
by Alex Alex
HTML
<canvas width="500" height="550" id="canvas"></canvas>
JavaScript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var W = canvas.width = window.innerWidth;
var H = 550;
var mp = 45; //max particles
var particles = [];
var PI2 = Math.PI * 2;
var reqAnimFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
for ( var i = 0; i < mp; i++ ) {
particles.push({
x: Math.floor(Math.random()*W), //x-coordinate
y: Math.floor(Math.random()*H), //y-coordinate
d: Math.floor(Math.random()*(12 - 1) + 1), //density
r: Math.floor(Math.random()*(70 - 10) + 10)
})
}
ctx.globalAlpha = Math.random()*(1 - 0.1) + 0.1;
function animate() {
reqAnimFrame(animate);
for ( var i = 0; i < mp; i++ ) {
var p = particles[i];
p.x += p.d;
if(p.x >= W + p.r){
p.x = -300;
p.y = ~~(Math.random()*H);
}
ctx.clearRect(0, 0, W, H);
for ( var j = 0; j < mp; j++ ) {
var p = particles[j];
ctx.beginPath();
ctx.fillStyle = "rgb(51,51,51)";
ctx.arc(p.x, p.y, p.r, 0, PI2, false);
ctx.fill();
ctx.closePath();
}
}
}
animate();