JSFiddle - React, Tailwind, and code Playground
by jcubed111
HTML
<canvas id="main"></canvas>
CSS
body{
background: #100a15;
}
JavaScript
function rand(min, max) {
return Math.random() * (max - min) + min;
}
class _Color{
constructor(r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
normalize(i) {
return Math.max(Math.min(Math.round(i), 255), 0);
}
toString() {
return `rgba(${this.normalize(this.r)}, ${this.normalize(this.g)}, ${this.normalize(this.b)}, ${this.a / 255.0})`;
}
clone() {
return new _Color(this.r, this.g, this.b, this.a);
}
lerp(other, f) {
return new _Color(
this.r * (1.0 - f) + other.r * f,
this.g * (1.0 - f) + other.g * f,
this.b * (1.0 - f) + other.b * f,
this.a * (1.0 - f) + other.a * f,
);
}
times(rf, gf, bf, af) {
return new _Color(
this.r * rf,
this.g * gf,
this.b * bf,
this.a * af,
);
}
}
function Color(hex) {
if(hex[0] == '#') hex = hex.slice(1);
if(hex.length <= 4) {
hex = hex.split('').map(c => c + c).join('');
}
if(hex.length < 8) hex += 'ff';
const i = parseInt(hex, 16);
return new _Color(
i >> 24 & 0xff,
i >> 16 & 0xff,
i >> 8 & 0xff,
i & 0xff,
);
}
const canvas = document.getElementById('main');
const ctx = canvas.getContext('2d');
const pixelSize = 4;
const particles = [];
class Particle{
constructor(x, y, color) {
this.x = this.sx = x;
this.y = this.sy = y;
this.color = color;
this.vel = {
x: 3 * Math.sin(this.y * 0.5 + this.x * 0.1) + rand(-1, 1),
y: Math.sin(this.y * 0.1 + this.x * 0.8) + rand(-1, 1),
};
this.opacity = rand(1.25, 1.75);
this.opacityVel = rand(-1.5, -0.5);
this.age = 0.0;
}
step(dt) {
this.age += dt;
// dist is based on integrating d/dx = 1 - 1 / (4t + 1.1)
const dist = this.age - 0.25 * Math.log(4/1.1 * this.age + 1);
this.x =...