JSFiddle - React, Tailwind, and code Playground
HTML
<canvas class="canvas"></canvas>
CSS
html, body {
margin: 0; padding: 0;
background: #fff;
overflow: hidden;
}
#canvas {
width: 100vw;
height: 100vh;
}
JavaScript
//Helper functions
//Extend an object's properties to a default object
Object.defineProperty(Object.prototype, "extend", {
value: function (defaults) {
for (var prop in defaults)
if (this.hasOwnProperty(prop)) defaults[prop] = this[prop];
return defaults;
}
});
function ParticleRenderer(element, initSettings) {
"use strict";
//Globals
var ctxArc, ctxLine, req,
localSettings = {},
particles = [];
//Default settings that initSettings or newSettings will be merged into
var defaultSettings = {
particles: 100, //Number of particles to render
connectDistance: element.width / element.height * 20, //Maximum distance for particles to be "connected" with a line
frozen: false, //Will not animate if frozen is true
fill: "rgba(170,230,200,1)", //Colour of circles
stroke: "rgba(170,200,230,1)" //Colour of lines
};
//Particle object used as a structure
var Particle = function (ops) {
this.id = ops.id;
this.x = ops.x;
this.y = ops.y;
this.size = ops.size || 3;
this.vx = ops.vx || rand(-1, 1) / 10;
this.vy = ops.vy || rand(-1, 1) / 10;
};
//Clear both canvasses entirely and redraw
function animate() {
ctxArc.clearRect(0, 0, element.width, element.height);
ctxLine.clearRect(0, 0, element.width, element.height);
drawFrame();
req = requestAnimationFrame(animate);
}
//Draws all particles and lines between
function drawFrame() {
var j, dist, p, p2, opacity,
maxDist = localSettings.connectDistance,
i = particles.length;
//Begin drawing circle paths
ctxArc.beginPath();
while (i--) {
p = particles[i];
//Move particle (except mouse-controller particle)
if (i != 0) {
p.x += p.vx;
p.y += p.vy;
}
//Keep particle in-frame by wrapping it to 0
p.y = p.y >...