JSFiddle - React, Tailwind, and code Playground
by ryanwfiorini
HTML
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas></canvas>
</body>
</html>
CSS
html { height: 100%; }
body {
margin: 0;
padding: 0;
background-color: #222;
height: 100%;
}
JavaScript
(function() {
var Particle = function(x, y, vx, vy) {
this.x = x || 0;
this.y = y || 0;
this.vx = vx || 0;
this.vy = vy || 0;
this.update = function (vx, vy) {
vx = vx || 0,
vy = vy || 0;
this.x += this.vx + vx;
this.y += this.vy + vy;
};
};
var ParticleSystem = function(container, center, count) {
var i = 0,
c = container.getContext('2d');
count = count || 0;
this.particles = [];
this.center = {
x: center.x || 0,
y: center.y || 0
};
// Initialization
for ( ; i < count ; ++i ) {
var x = this.center.x,
y = this.center.y,
vx = Math.random() * 3 - 1.5,
vy = Math.random() * 3 - 1.5;
this.particles.push(new Particle(x, y, vx, vy));
}
this.update = function() {
for ( i = 0 ; i < count ; ++i ) {
// We don't want to process particles that
// we can't see anymore
if (this.particles[i].x > 0 &&
this.particles[i].x < container.width &&
this.particles[i].y > 0 &&
this.particles[i].y < container.height) {
this.particles[i].update();
c.fillRect(this.particles[i].x, this.particles[i].y, 5, 5);
} else {
this.particles[i].x = this.center.x;
this.particles[i].y = this.center.y;
}
}
};
};
// shim layer with setTimeout fallback by Paul Irish
// Used as an efficient and browser-friendly
// replacement for setTimeout or setInterval
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// Call the init() function on load
init();
function init() {
// Get a reference to the canvas object...