JSFiddle - React, Tailwind, and code Playground

by Scott Kaye

CSS

canvas {
    outline: 1px solid red;
    margin: 5px;
    opacity: 0.5;
}

JavaScript

let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");

canvas.width = 50;
canvas.height = 300;

document.body.appendChild(canvas);

ctx.fillStyle = "#000";

let p = [];

function rand(min, max) {
    return (Math.random() * (max - min + 1) + min);
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    let i, l;
    for (i = 0, l = p.length; i < l; ++i) {
        p[i].vy += 0.3;
        p[i].x += p[i].vx;
        p[i].y += p[i].vy;

        if (p[i].x + p[i].w / 2 <= 0 || p[i].x + p[i].w / 2 >= canvas.width) {
            p[i].vx *= -1;
        }

        ctx.fillRect(p[i].x - p[i].w / 2, p[i].y - p[i].h / 2, p[i].w, p[i].h);

        if (p[i].y + p[i].h > canvas.height) {
            p.splice(i, 1);
            --i;
            --l;
        }
    }

    requestAnimationFrame(draw);
}

draw();

setInterval(() => {
    p.push({
        x: 50,
        y: 80,
        vx: rand(-2, -5),
        vy: rand(-4, -6),
        w: 3,
        h: 3
    });
}, 100);