Pixel FX Code Example

document.getElementById('pixel-1').addEventListener('click',function(){
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 399.5;
canvas.height = 420;
ctx.drawImage(image1, 0, 0, canvas.width, canvas.height);
const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
ctx.clearRect(0,0, canvas.width, canvas.height);

let particlesArray = [];
const numberOfParticles = 10000;

let mappedImage = [];
// This for loop uses the canvas height and canvas width to iterate over the
// image data gathered in the variable pixels. it is a nested for loop, the
// the height for loop will be called 999 times
for (let y = 0; y < canvas.height; y++ ) {
    let row = [];
    for (let x = 0; x < canvas.width; x++) {
        const red = pixels.data[(y * 4 * pixels.width) + (x * 4)];
        const green = pixels.data[(y * 4 * pixels.width) + (x * 4 + 1)];
        const blue = pixels.data[(y * 4 * pixels.width) + (x * 4 + 2)];
        // Hoisting allows the below function to be called up in this loop.
        const brightness = calculateRelativeBrightness(red, green, blue);
        const cell = [
            cellBrightness = brightness,
        ];
        row.push(cell);
    }
    mappedImage.push(row);
}

function calculateRelativeBrightness(red, green, blue) {
    return Math.sqrt(
        (red * red) * 0.299 +
        (green * green) * 0.587 +
        (blue * blue) * 0.114
    )/100;
}

class Particle {
    constructor(){
        this.x = Math.random() * canvas.width;
        this.y = 0;
        this.speed = 0;
        this.velocity = Math.random() * 8;
        this.size = Math.random() * 1 + 1;
        this.position1 = Math.floor(this.y);
        this.position2 = Math.floor(this.x);
    }

    update(){
        this.position1 = Math.floor(this.y);
        this.position2 = Math.floor(this.x);
        this.speed = mappedImage[this.position1][this.position2][0];
        let movement = (2.5 - this.speed) + this.velocity;

        this.y += movement;
        if(this.y >= canvas.height) {
            this.y = 0;
            this.x = Math.random() * canvas.width;
        }
    }

    draw(){
        ctx.beginPath();
        ctx.fillStyle = '#03cea4';
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
    }
}
function init(){
    for (let i = 0; i < numberOfParticles; i++){
        particlesArray.push(new Particle);
    }
}

init();

function animate(){
    // ctx.drawImage(image1, 0, 0, canvas.width, canvas.height);
    ctx.globalAlpha = 0.05;
    ctx.fillStyle = '#450920';
    ctx.fillRect(0,0, canvas.width, canvas.height);
    for (let i = 0; i < particlesArray.length; i++){
        particlesArray[i].update();
        particlesArray[i].draw();
    }
    requestAnimationFrame(animate);
}
animate();

});