Static

classic TV static via canvas

by kpowz

HTML

<canvas></canvas>

CSS

body {
    margin: 0;
    overflow: hidden;
}

JavaScript

var canvas = document.querySelector('canvas'),
    ctx = canvas.getContext('2d'),
    noiseTexture,
    tvTexture,
    noisePosX = 0,
    noisePosY = 0,
    WebAudio = (window.AudioContext || window.webkitAudioContext),
    requestFrame = (window.requestAnimationFrame ||       
                    window.webkitRequestAnimationFrame ||
                    window.mozRequestAnimationFrame),
                    
    audio = new WebAudio(),
    i;

function createTexture(width, height, generator) {
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
    
    canvas.width = width;
    canvas.height = height;
    generator(canvas, ctx);
    return canvas;
}

function noiseGenerator(canvas, ctx) {
    var i, j;
    
    ctx.fillStyle = 'white';
    ctx.globalAlpha = 1;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    //why not imageData? because performance sucked with it
    //on my old crap test-computer, dunno why.
    ctx.fillStyle = 'black';
    for (i = 0; i < canvas.width; i += 1) {
        for (j = 0; j < canvas.height; j += 1) {
            ctx.globalAlpha = Math.random();
            ctx.fillRect(i, j, 1, 1);
        }
    }
}

function playAudioNoise() {
    var i, j,
        noise = audio.createBufferSource(),
        seconds = 10,
        size = audio.sampleRate * seconds,
        lowPassLength = 7,
        noiseBuffer,
        noiseData;
    
    noiseBuffer = audio.createBuffer(1, size, audio.sampleRate);
    noiseData = noiseBuffer.getChannelData(0);
    
    for (i = 0; i < size; i += 1) {
        noiseData[i] = Math.random() - 0.5;
    }
    
    for (i = 0; i < size; i += 1) {
        for (j = 0; j < lowPassLength; j += 1) {
            noiseData[i] += noiseData[(i + j) % size];
        }
        
        noiseData[i] /= lowPassLength;
    }
    
    noise.buffer = noiseBuffer;
    noise.connect(audio.destination);
    noise.loop = true;
    noise.start(0);
    
    return noise;
}

function...