Skip to main content
Articles

Add A Confetti JavaScript To Your Site For No Reason

49
0

Add this JavaScript to the footer of your website to create a fun confetti effect.
This one is free and you can just copy and paste. Change the DURATION to set it to run longer or shorter.


<script>
(function () {
  const DURATION = 30000; // 30 seconds

  // Create canvas
  const canvas = document.createElement("canvas");
  canvas.style.position = "fixed";
  canvas.style.top = "0";
  canvas.style.left = "0";
  canvas.style.width = "100%";
  canvas.style.height = "100%";
  canvas.style.pointerEvents = "none";
  canvas.style.zIndex = "9999";
  document.body.appendChild(canvas);

  const ctx = canvas.getContext("2d");
  let width = canvas.width = window.innerWidth;
  let height = canvas.height = window.innerHeight;

  const colors = ["#FFC700", "#FF4D4D", "#2E86FF", "#2ECC71", "#9B59B6"];
  const confettiCount = 180;
  const confetti = [];

  for (let i = 0; i < confettiCount; i++) {
    confetti.push({
      x: Math.random() * width,
      y: Math.random() * height - height,
      r: Math.random() * 6 + 4,
      d: Math.random() * confettiCount,
      color: colors[Math.floor(Math.random() * colors.length)],
      tilt: Math.random() * 10 - 10,
      tiltAngle: 0,
      tiltAngleIncrement: Math.random() * 0.05 + 0.03
    });
  }

  let animationFrame;

  function draw() {
    ctx.clearRect(0, 0, width, height);
    confetti.forEach(c => {
      ctx.beginPath();
      ctx.lineWidth = c.r;
      ctx.strokeStyle = c.color;
      ctx.moveTo(c.x + c.tilt, c.y);
      ctx.lineTo(c.x, c.y + c.tilt + c.r);
      ctx.stroke();
    });
    update();
  }

  function update() {
    confetti.forEach(c => {
      c.tiltAngle += c.tiltAngleIncrement;
      c.y += (Math.cos(c.d) + 3 + c.r / 2) / 2;
      c.x += Math.sin(c.d);
      c.tilt = Math.sin(c.tiltAngle) * 15;

      if (c.y > height) {
        c.y = -10;
        c.x = Math.random() * width;
      }
    });
  }

  function animate() {
    draw();
    animationFrame = requestAnimationFrame(animate);
  }

  animate();

  // Stop after 30 seconds
  setTimeout(() => {
    cancelAnimationFrame(animationFrame);
    canvas.remove();
  }, DURATION);

  // Handle resize
  window.addEventListener("resize", () => {
    width = canvas.width = window.innerWidth;
    height = canvas.height = window.innerHeight;
  });
})();
</script>

Corner Icon Render
Corner Icon Render
Corner Icon Render
Corner Icon Render How Can I Help You?