JSFiddle - React, Tailwind, and code Playground

by joecritch

HTML

<h1>Brownie in Motion&trade; by <a href="http://twitter.com/joecritchley">Joe Critchley</a></h1>

<canvas id="brownies" width="700" height="500"></canvas>

CSS

* { margin: 0; padding: 0; }
body { background: #eee; }
h1 { background: black; color: white; font-size: 18px; padding: 10px; position: absolute; bottom: 0; left: 0; right: 0; font-family: sans-serif; text-align: center; }
h1 a { color: white; }

JavaScript

// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function(/* function */ callback, /* DOMElement */ element){
            window.setTimeout(callback, 1000 / 60);
          };
})();

var num = 50,
    friction = 0.95,
    brownies = [ ],
    canvas = document.getElementById('brownies'),
    ctx = canvas.getContext('2d');

function Brownie(radius, x, y, color) {    
    this.radius = radius;
    this.x = x;
    this.y = y;
    this.vx = 0;
    this.vy = 0;
    this.color = color;

    this.draw();    
}

Brownie.prototype.draw = function() {
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,true);
    ctx.closePath();
    ctx.fill();
};

Brownie.prototype.move = function() {
    this.vx += Math.random() * 0.2 - 0.1;
    this.vy += Math.random() * 0.2 - 0.1;
    this.x += this.vx;
    this.y += this.vy;
    this.vx *= friction;
    this.vy *= friction;
    
    if(this.x > canvas.width) {
        this.x = 0;
    }
    else if(this.x < 0) {
        this.x = canvas.width;
    }
    
    if(this.y > canvas.height) {
        this.y = 0;
    }
    else if(this.y < 0) {
        this.y = canvas.height;
    }
    
    this.draw();
    
};

function init() {
    
    // Make the canvas full screen
    canvas.width = document.width;
    canvas.height = document.height;
    
    // Create the brownies 
    for(var i = 0; i < num; i++) {
        var brownie = new Brownie(5, Math.random() * canvas.width, Math.random() * canvas.height, 'brown');
        brownie.draw();
        brownies.push(brownie);
    }
    
    // Constantly move those brownies.
    (function tick() {
        canvas.width = canvas.width;
        for(var i = 0; i < num; i++) {
  ...