JSFiddle - React, Tailwind, and code Playground
by kariboo84
HTML
<canvas id=television width=160 height=222>
</canvas>
CSS
canvas {
display: block;
border: 1px solid #333;
-webkit-border-radius: 10px /15px;
-moz-border-radius: 10px / 15px;
border-radius: 10px / 15px;
margin: 20px auto 0;
-webkit-transform: scaleX(2.0);
-moz-transform: scaleX(2.0);
-o-transform: scaleX(2.0);
-ms-transform: scaleX(2.0);
transform: scaleX(2.0);
}
.frame-rate {
margin-top: 45px;
}
.frame-rate label {
margin-right: 7px;
}
.frame-rate label:after {
content: ":";
}
.frame-rate input {
width: 4em;
}
.frame-rate span {
font-size: 12px;
}
JavaScript
// define a reference to the canvas's 2D context
var context = television.getContext('2d');
// create a buffer to hold the pixel data
var pixelBuffer = context.createImageData(television.width, television.height);
function drawStatic() {
var color,
data = pixelBuffer.data,
index = 0,
len = data.length;
while (index < len) {
// choose a random grayscale color
color = Math.floor(Math.random() * 0xff);
// red, green and blue are set to the same color
// to result in a random gray pixel
data[index++] = data[index++] = data[index++] = color;
// the fourth multiple is always completely opaque
data[index++] = 0xff; // alpha
}
// flush our pixel buffer to the canvas
context.putImageData(pixelBuffer, 0, 0);
};
// rAF
window.requestAnimationFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(f) {
window.setTimeout(f,1e3/60);
}
}();
var limitLoop = function (fn, fps) {
// Use var then = Date.now(); if you
// don't care about targetting < IE9
var then = new Date().getTime();
// custom fps, otherwise fallback to 60
fps = fps || 60;
var interval = 1000 / fps;
return (function loop(time){
requestAnimationFrame(loop);
// again, Date.now() if it's available
var now = new Date().getTime();
var delta = now - then;
if (delta > interval) {
// Update time
// now - (delta % interval) is an improvement over just
// using then = now, which can end up lowering overall fps
then = now - (delta % interval);
// call the fn, passing current fps to it
fn(frames);
}
...