Created
April 30, 2019 01:45
-
-
Save Lavrend/cce8a87c641492de1113d93b698ca77f to your computer and use it in GitHub Desktop.
Add noise effect for canvas bg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const noise = (canvas) => { | |
const ctx = canvas.getContext('2d'); | |
const noiseData = []; | |
let wWidth; | |
let wHeight; | |
let loopTimeout; | |
let resizeThrottle; | |
let frame = 0; | |
// Create Noise | |
const createNoise = () => { | |
const idata = ctx.createImageData(wWidth, wHeight); | |
const buffer32 = new Uint32Array(idata.data.buffer); | |
const len = buffer32.length; | |
for (let i = 0; i < len; i += 1) { | |
if (Math.random() < 0.5) buffer32[i] = 0xff000000; | |
} | |
noiseData.push(idata); | |
}; | |
// Play Noise | |
const paintNoise = () => { | |
if (frame === 9) frame = 0; | |
else frame += 1; | |
ctx.putImageData(noiseData[frame], 0, 0); | |
}; | |
// Loop | |
const loop = () => { | |
paintNoise(frame); | |
loopTimeout = setTimeout(() => { | |
requestAnimationFrame(loop); | |
}, (1000 / 25)); | |
}; | |
// Setup | |
const setup = () => { | |
wWidth = window.innerWidth; | |
wHeight = window.innerHeight; | |
canvas.width = wWidth; | |
canvas.height = wHeight; | |
for (let i = 0; i < 10; i += 1) { | |
createNoise(); | |
} | |
loop(); | |
}; | |
const resizeHandler = () => { | |
clearTimeout(resizeThrottle); | |
resizeThrottle = setTimeout(() => { | |
clearTimeout(loopTimeout); | |
setup(); | |
}, 200); | |
}; | |
// Clear | |
const clear = () => { | |
clearTimeout(resizeThrottle); | |
clearTimeout(loopTimeout); | |
window.removeEventListener('resize', resizeHandler); | |
}; | |
setup(); | |
window.addEventListener('resize', resizeHandler, false); | |
return clear; | |
}; | |
export default noise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment