JS noise

Quickly draw some noise on a canvas

by Guillaume Lafarge

HTML

<canvas id="canvas"></canvas>

CSS

body { margin:0; padding:0; overflow:hidden; }

JavaScript

// ===========================================
// Initialization
// ===========================================

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext('2d'),
    contrast = 150, // x/255
    animated = true;

// ===========================================
// Noise drawing
// ===========================================

function noise(ctx) {
    var w = ctx.canvas.width,
        h = ctx.canvas.height,
        idata = ctx.createImageData(w, h),
        buffer32 = new Uint32Array(idata.data.buffer),
        len = buffer32.length;

    for (i = 0; i < len; i++) {
        buffer32[i] = ((contrast * Math.random()) | 0) << 24;
    }

    ctx.putImageData(idata, 0, 0);
}


// ===========================================
// Loop / animate
// ===========================================

(function loop() {
		noise(ctx);
    
    if (animated == true) {
        requestAnimationFrame(loop);
    }
})();

// ===========================================
// Resize stuff
// ===========================================

function resize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}
resize();
window.onresize = resize;