noise test
by John Doe
HTML
<canvas id="noise" class="static"></canvas>
<div id="background"></div>
CSS
#noise, #background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
#noise {
z-index: 10;
opacity: 0.05;
}
#background {
background-image: linear-gradient(to right bottom, #fbf9d0, #d1dda1, #a1c378, #69a955, #0e903a);
z-index: 9;
opacity: 0.8;
}
JavaScript
const noise = () => {
let canvas, ctx;
let windowWidth, windowHeight;
let noiseData = [];
let frame = 0;
let loopTimeout;
// Create Noise
const createNoise = () => {
const idata = ctx.createImageData(windowWidth, windowHeight);
const buffer32 = new Uint32Array(idata.data.buffer);
const len = buffer32.length;
for (let i = 0; i < len; i++) {
if (Math.random() < .5) {
buffer32[i] = 0xff000000;
}
}
noiseData.push(idata);
};
// Play Noise
const paintNoise = () => {
if (frame === 9) {
frame = 0;
} else {
frame++;
}
ctx.putImageData(noiseData[frame], 0, 0);
};
// Loop
const loop = () => {
paintNoise(frame);
loopTimeout = window.setTimeout(() => {
window.requestAnimationFrame(loop);
}, (1000 / 25));
};
// Setup
const setup = () => {
windowWidth = window.innerWidth;
windowHeight = window.innerHeight;
canvas.width = windowWidth;
canvas.height = windowHeight;
for (let i = 0; i < 10; i++) {
createNoise();
}
canvas = document.getElementById('noise');
if (canvas.classList.contains('static')){
paintNoise(frame);
} else {
loop();
}
};
// Reset
let resizeThrottle;
const reset = () => {
window.addEventListener('resize', () => {
window.clearTimeout(resizeThrottle);
resizeThrottle = window.setTimeout(() => {
window.clearTimeout(loopTimeout);
setup();
}, 200);
}, false);
};
// Init
const init = (() => {
canvas = document.getElementById('noise');
ctx = canvas.getContext('2d');
setup();
})();
};
noise();