JSFiddle - React, Tailwind, and code Playground

by salmaan25

HTML

<canvas id="myCanvas" width="800" height="400"></canvas>

CSS

body {
  margin: 0;
  overflow: hidden;
}

JavaScript

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const confettiPieces = [];
const emitter = { x: canvas.width / 2, y: canvas.height / 2 }; // Emitter point

// Function to generate random number within a range
function getRandomNumber(min, max) {
  return Math.random() * (max - min) + min;
}

// Function to generate a random confetti piece
function createConfettiPiece() {
  const x = emitter.x;
  const y = emitter.y;
  const angle = getRandomNumber(0, Math.PI * 2);
  const rotation = getRandomNumber(-0.2, 0.2);
  const size = getRandomNumber(10, 20);
  const color = `rgb(${getRandomNumber(0, 255)}, ${getRandomNumber(0, 255)}, ${getRandomNumber(0, 255)})`;

  return {
    x,
    y,
    angle,
    rotation,
    size,
    color
  };
}

// Function to update and draw confetti pieces
function updateConfetti() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  confettiPieces.forEach((confetti) => {
    confetti.x += Math.cos(confetti.angle) * 2;
    confetti.y += Math.sin(confetti.angle) * 2;
    confetti.angle += confetti.rotation;

    ctx.beginPath();
    ctx.arc(confetti.x, confetti.y, confetti.size, 0, Math.PI * 2);
    ctx.fillStyle = confetti.color;
    ctx.closePath();
    ctx.fill();

    if (confetti.x > canvas.width || confetti.x < 0 || confetti.y > canvas.height || confetti.y < 0) {
      confetti.x = emitter.x;
      confetti.y = emitter.y;
    }
  });

  requestAnimationFrame(updateConfetti);
}

// Create initial confetti pieces
for (let i = 0; i < 100; i++) {
  confettiPieces.push(createConfettiPiece());
}

// Start the animation
updateConfetti();