JSFiddle - React, Tailwind, and code Playground
by lbstr
HTML
<div id="canvas-wrap"></div>
<button id="b">Stop</button>
JavaScript
var MGR = function(c, w, h, fps){
var self = this,
ctx = c.getContext("2d"),
cx = Math.round(w/2),
cy = Math.round(h/2),
cvx = Math.random() * 10 + 10,
cvy = Math.random() * 10 + 10;
this.stop = false;
function render(){
ctx.fillStyle = "rgb(0, 0, 0)";
self.rect(ctx,0,0,w,h);
self.addNoise(ctx,cx,cy,w,h);
cx += cvx;
if (cx > w) {
cvx = -1 * Math.abs(cvx);
}
else if (cx < 0) {
cvx = Math.abs(cvx);
}
cy += cvy;
if (cy > h) {
cvy = -1 * Math.abs(cvy);
}
else if (cy < 0) {
cvy = Math.abs(cvy);
}
if (self.stop) { return; }
requestAnimationFrame(render);
}
render();
};
MGR.prototype.rect = function(ctx,x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
};
MGR.prototype.dot = function(ctx,x,y) {
this.rect(ctx,x,y,1,1);
};
MGR.prototype.addNoise = function(ctx,cx,cy,w,h) {
var maxD = Math.sqrt(w*w + h*h),
x = w,
y, d,
isHit = function(d) {
var p = Math.pow(1 - (d / maxD), 50);
return Math.random() < p;
};
ctx.fillStyle = "rgb(60, 140, 250)";
while(x--) {
y = h;
while(y--) {
d = Math.sqrt(Math.pow(cx - x, 2) + Math.pow(cy - y, 2));
if (isHit(d)) {
this.dot(ctx, x, y);
}
}
}
};
MGR.prototype.kill = function(){
this.stop = true;
};
(function(){
var w = -50 + (window.innerWidth || document.body.clientWidth),
h = -50 + (window.innerHeight || document.body.clientHeight);
$('#canvas-wrap').append('<canvas id="c" width="'+w+'" height="'+h+'"></canvas>');
var mgr = new MGR(document.getElementById("c"), w, h, 100);
$('#b').click(function(){mgr.kill();});
})();