JSFiddle - React, Tailwind, and code Playground

by zenojevski

HTML

<canvas id="canvas"></canvas>
<script src="https://rawgithub.com/owencm/javascript-jpeg-encoder/master/jpeg_encoder_basic.js"></script>

CSS

html, body {
    margin: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

canvas {
    width: 100%;
    height: 100%;
}

JavaScript

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    encoder = new JPEGEncoder(15), // low quality
    duration = 1 // slide duration,
    slide = 1;

// Scale slightly to introduce imperfections
var scale = 0.74,
    ww = canvas.width = canvas.offsetWidth * scale,
    hh = canvas.height = canvas.offsetHeight * scale;

function drawRect(color) {
    var x1 = Math.random() * ww,
        y1 = Math.random() * hh,
        x2 = Math.random() * ww,
        y2 = Math.random() * hh;
    ctx.fillStyle = color;
    ctx.fillRect(x1, y1, x2, y2);
}

function drawStatus() {
    var currentSlide = ('000' + slide).slice(-4);
    ctx.fillStyle = "black";
    ctx.font = "bold 8.4pt courier"; // Would like a bitmap font here
    ctx.fillText("aqua.flv - slide " + currentSlide, 10, hh-20);
    slide += 1
}

function drawFrame() {
    // Opaque background
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, ww, hh);
    // Red rectangle is always in front
    drawRect('#0000ff');
    drawRect('#ff0000');
    // Draw decorations and jpegize
    drawStatus();
    disturbPixels();
}

function disturbPixels() {
    // Work around the fact that the encoder
    // outputs image URIs.
    var img = document.createElement("img");
    // Note: we draw the canvas twice this way.
    // We should use an offscreen canvas.
    img.src = encoder.encode(
        ctx.getImageData(0, 0, ww, hh));
    img.onload = function(){
        ctx.drawImage(this, 0, 0);
    }
}

setInterval(drawFrame, duration * 1000);
drawFrame();