Canvas - Realtime

by Nick Karnik

HTML

<canvas id="can" width=600 height=600></canvas>
<div id=fps></div>
<button onclick="fill()">Start</button>
<button onclick="cancelAnimationFrame(window.animId)">Stop</button>

CSS

canvas {
    opacity: 0.4;
}

JavaScript

c = can.getContext('2d');

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
var count = 0;

function fill() {

    c.clearRect(0, 0, 600, 600);
    c.fillStyle = getRandomColor();
    var a =         "transparent";
    var b =         getRandomColor();
    
    for(var row=0; row<100; row++){
        for (var col=0; col<100; col++)
        {        
                
            //c.fillStyle = (row % 2 == 0 || col % 2 == 0) ? "green" : "red";
            //c.clearRect(row * 4, col * 4, 4, 4);
            c.fillStyle = a;
            c.fillRect(row * 4, col * 4, 4, 4);
            c.fillStyle = b;            
//c.fillStyle = getRandomColor();            
            c.fillRect(row * 4, col * 4, 4, 4);
        }
    }
    
    var thisFrameFPS = 1000 / ((now = new Date) - lastUpdate);

    if (now != lastUpdate) {
        fps += (thisFrameFPS - fps) / fpsFilter;
        lastUpdate = now;
    }

    window.animId = requestAnimationFrame(fill);
}

var fps = 0, now, lastUpdate = (new Date) * 1;
// The higher this value, the less the FPS will be affected by quick changes
// Setting this to 1 will show you the FPS of the last sampled frame only

var fpsFilter = 50;


var fpsOut = document.getElementById('fps');
setInterval(function () {
    fpsOut.innerHTML = fps.toFixed(1) + "fps";
}, 1000);