It's Christmas, get a 30% OFF. Apply code XMAS at checkout.

← Back to all tutorials

How to create a confetti animation effect using Tailwind CSS and JavaScript

#
Published and written on Oct 08 2024 by Michael Andreuzza

Good morning everyone, today we are going to create a simple confetti animation effect using Tailwind CSS and JavaScript, just a fun way to celebrate our users achievements!

What is a Confetti Animation?

A confetti animation mimics the effect of colorful paper pieces or streamers falling through the air, often used during celebrations. In web design, this effect can be created using CSS and JavaScript to animate small elements (usually small shapes or images) that move across the screen in a random pattern, imitating the joyful, chaotic nature of real-life confetti.

Confetti pieces (or “particles”) can vary in size, shape, color, and behavior. Some confetti animations are lightweight, using basic shapes and movement, while others can include more complex behaviors and physics-like effects.

Use Cases

Confetti animations are used to celebrate and engage users in various scenarios. Some common use cases include:

  • Completion of an important action: Celebrate a user completing a task like signing up, making a purchase, or finishing a tutorial.

  • Achievement or milestone celebration: Trigger the effect when a user reaches a milestone, such as finishing a project or earning a reward.

  • Gamification elements: In apps using gamification (e.g., fitness, education), confetti can make achievements feel more rewarding.

  • Marketing and promotions: Celebrate events like an anniversary or sale on e-commerce sites, adding a festive touch to your platform.

  • Social Media: Use confetti-like animations for milestones (e.g., reaching a follower goal or high post engagement).

Let’s get ready to create this fun and dynamic effect to make your app more engaging!

Let’s get started by writting the html

First, we need to create a button to be able to trigger the animation and also a canvas element to draw the confetti animation.

The button

ID’s

  • id="confettiButton": This line of code will define the id of the button.
<button
   id="confettiButton">
Celebrate!
</button>

The canvas

The canvas element is used to draw the confetti animation as mentioned earlier, so we need to define it with the following properties: ID’s

  • id="confettiCanvas": This line of code will define the id of the canvas. Classes
  • fixed: This class will make the canvas element fixed on the screen.
  • top-0: This class will position the canvas element at the top of the screen.
  • left-0: This class will position the canvas element at the left of the screen.
  • w-full: This class will make the canvas element take up the full width of the screen.
  • h-full: This class will make the canvas element take up the full height of the screen.
  • pointer-events-none: This class will make the canvas element not respond to any pointer events, such as clicks or hovers.
<canvas
id="confettiCanvas"
class="fixed top-0 left-0 w-full h-full pointer-events-none">
</canvas>

The whole html makup code

Note: The classes for the button are omitted because they are irrelevant to the animation and for brevity

<button
   id="confettiButton">
Celebrate!
</button>
<canvas
id="confettiCanvas"
class="fixed top-0 left-0 w-full h-full pointer-events-none">
</canvas>

Now, let’s write the JavaScript code

Here is where the magic happens, we need to write the JavaScript code that will create the confetti animation and make it interactive. The idea is to create a canvas element, get its context, get the button element, set the canvas dimensions, define the colors of the confetti, define the number of confettis, define the gravity, the terminal velocity, the drag, and finally create the confettis and animate them.

The variables

  • const canvas = document.getElementById("confettiCanvas"); This line of code will get the canvas element with the id of “confettiCanvas” and store it in a variable called canvas.
  • const ctx = canvas.getContext("2d"); This line of code will get the context of the canvas element and store it in a variable called ctx.
  • const confettiButton = document.getElementById("confettiButton"); This line of code will get the button element with the id of “confettiButton” and store it in a variable called confettiButton.
  • canvas.width = window.innerWidth; This line of code will set the width of the canvas element to the width of the window.
  • canvas.height = window.innerHeight; This line of code will set the height of the canvas element to the height of the window.
  • const confettiColors = ["#5cffe4", "#a9ff03", "#fd02d1", "#1e1e59", "#9645f6"]; This line of code will define an array of colors for the confettis.
  • const confettiCount = 200; This line of code will define the number of confettis to be created.
  • const gravity = 0.5; This line of code will define the gravity of the confettis.
  • const terminalVelocity = 5; This line of code will define the terminal velocity of the confettis.
  • const drag = 0.075; This line of code will define the drag of the confettis.
  • const confettis = []; This line of code will define an empty array to store the confettis.
const canvas = document.getElementById("confettiCanvas");
  const ctx = canvas.getContext("2d");
  const confettiButton = document.getElementById("confettiButton");
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const confettiColors = [
    "#5cffe4",
    "#a9ff03",
    "#fd02d1",
    "#1e1e59",
    "#9645f6",
  ];
  const confettiCount = 200;
  const gravity = 0.5;
  const terminalVelocity = 5;
  const drag = 0.075;
  const confettis = [];

Defining the Confetti class

The Confetti class will be used to create the confettis and define their properties. The class will have the following properties:

Color property (constructor)
  • x: This property will be used to store the x-coordinate of the confetti.
  • y: This property will be used to store the y-coordinate of the confetti.
  • w: This property will be used to store the width of the confetti.
  • h: This property will be used to store the height of the confetti.
  • color: This property will be used to store the color of the confetti.
  • dx: This property will be used to store the x-coordinate of the confetti’s movement.
  • dy: This property will be used to store the y-coordinate of the confetti’s movement.
 constructor(color) {
     this.x = Math.random() * canvas.width;
     this.y = Math.random() * canvas.height - canvas.height;
     this.w = Math.random() * 10 + 5;
     this.h = Math.random() * 5 + 5;
     this.color = color;
     this.dx = Math.random() * 5 - 2.5;
     this.dy = Math.random() * -5 - 5;
 }
Updating the confetti’s position (update method)
  • this.dy += gravity;: This line of code will add the value of gravity to the dy property of the confetti.
  • this.x += this.dx;: This line of code will add the value of dx to the x property of the confetti.
  • this.y += this.dy;: This line of code will add the value of dy to the y property of the confetti.
  • if (this.y + this.h > canvas.height): This line of code will check if the y-coordinate of the confetti plus its height is greater than the height of the canvas.
  • this.dy *= -drag;: This line of code will multiply the value of dy by -drag.
  • this.y = canvas.height - this.h;: This line of code will set the y-coordinate of the confetti to the height of the canvas minus its height.
  • if (this.x + this.w > canvas.width || this.x < 0): This line of code will check if the x-coordinate of the confetti plus its width is greater than the width of the canvas or if the x-coordinate is less than 0.
  • this.dx *= -1;: This line of code will multiply the value of dx by -1.
update() {
    this.dy += gravity;
    this.x += this.dx;
    this.y += this.dy;
    if (this.y + this.h > canvas.height) {
        this.dy *= -drag;
        this.y = canvas.height - this.h;
    }
    if (this.x + this.w > canvas.width || this.x < 0) {
        this.dx *= -1;
    }
}
Drawing the confetti (draw method)
  • ctx.fillStyle = this.color;: This line of code will set the fill style of the canvas context to the color of the confetti.
  • ctx.fillRect(this.x, this.y, this.w, this.h);: This line of code will fill a rectangle with the x-coordinate, y-coordinate, width, and height of the confetti.
draw() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.w, this.h);
}

Thw whole Confetti class code

class Confetti {
    constructor(color) {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height - canvas.height;
        this.w = Math.random() * 10 + 5;
        this.h = Math.random() * 5 + 5;
        this.color = color;
        this.dx = Math.random() * 5 - 2.5;
        this.dy = Math.random() * -5 - 5;
    }
    update() {
        this.dy += gravity;
        this.x += this.dx;
        this.y += this.dy;
        if (this.y + this.h > canvas.height) {
            this.dy *= -drag;
            this.y = canvas.height - this.h;
        }
        if (this.x + this.w > canvas.width || this.x < 0) {
            this.dx *= -1;
        }
    }
    draw() {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.w, this.h);
    }
}

Creating the confettis function

The createConfettis function will be used to create the confettis and add them to the confettis array. The function will have the following properties:

  • for (let i = 0; i < confettiCount; i++): This line of code will create a loop that will iterate confettiCount times.
  • confettis.push(new Confetti(confettiColors[Math.floor(Math.random() * confettiColors.length)])): This line of code will push a new confetti object to the confettis array using the Confetti class and the confettiColors array.
 function createConfettis() {
     for (let i = 0; i < confettiCount; i++) {
         confettis.push(
             new Confetti(
                 confettiColors[Math.floor(Math.random() * confettiColors.length)]
             )
         );
     }
 }

The animate function

The animate function will be used to update and draw the confettis. The function will have the following properties:

  • ctx.clearRect(0, 0, canvas.width, canvas.height);: This line of code will clear the canvas by filling it with a transparent color.
  • confettis.forEach((confetti, index) => {: This line of code will iterate over each confetti in the confettis array and pass the confetti and its index to the anonymous function.
  • confetti.update();: This line of code will call the update method of the confetti.
  • confetti.draw();: This line of code will call the draw method of the confetti.
  • if (confetti.y > canvas.height): This line of code will check if the y-coordinate of the confetti is greater than the height of the canvas.
  • confettis.splice(index, 1);: This line of code will remove the confetti from the confettis array at the specified index.
  • if (confettis.length > 0): This line of code will check if the confettis array is not empty.
  • requestAnimationFrame(animate);: This line of code will call the animate function recursively using the requestAnimationFrame function.
function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    confettis.forEach((confetti, index) => {
        confetti.update();
        confetti.draw();
        if (confetti.y > canvas.height) {
            confettis.splice(index, 1);
        }
    });
    if (confettis.length > 0) {
        requestAnimationFrame(animate);
    }
}

The event listeners function for the button

The event listeners function will be used to add event listeners to the button.

  • confettiButton.addEventListener("click", () => {: This line of code will add an event listener to the button that will call the createConfettis function when the button is clicked.
  • createConfettis();: This line of code will call the createConfettis function.
  • animate();: This line of code will call the animate function.
confettiButton.addEventListener("click", () => {
    createConfettis();
    animate();
});

The event listeners function for the window

The event listeners function will be used to add event listeners to the window.

  • window.addEventListener("resize", () => {: This line of code will add an event listener to the window that will call the canvas.width = window.innerWidth; and canvas.height = window.innerHeight; functions when the window is resized.
  • canvas.width = window.innerWidth;: This line of code will set the width of the canvas to the width of the window.
  • canvas.height = window.innerHeight;: This line of code will set the height of the canvas to the height of the window.
window.addEventListener("resize", () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});

The whole JavaScript code

const canvas = document.getElementById("confettiCanvas");
  const ctx = canvas.getContext("2d");
  const confettiButton = document.getElementById("confettiButton");
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const confettiColors = [
    "#5cffe4",
    "#a9ff03",
    "#fd02d1",
    "#1e1e59",
    "#9645f6",
  ];
  const confettiCount = 200;
  const gravity = 0.5;
  const terminalVelocity = 5;
  const drag = 0.075;
  const confettis = [];
  class Confetti {
    constructor(color) {
      this.x = Math.random() * canvas.width;
      this.y = Math.random() * canvas.height - canvas.height;
      this.w = Math.random() * 10 + 5;
      this.h = Math.random() * 5 + 5;
      this.color = color;
      this.dx = Math.random() * 5 - 2.5;
      this.dy = Math.random() * -5 - 5;
    }
    update() {
      this.dy += gravity;
      this.x += this.dx;
      this.y += this.dy;
      if (this.y + this.h > canvas.height) {
        this.dy *= -drag;
        this.y = canvas.height - this.h;
      }
      if (this.x + this.w > canvas.width || this.x < 0) {
        this.dx *= -1;
      }
    }
    draw() {
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.w, this.h);
    }
  }
  function createConfettis() {
    for (let i = 0; i < confettiCount; i++) {
      confettis.push(
        new Confetti(
          confettiColors[Math.floor(Math.random() * confettiColors.length)]
        )
      );
    }
  }
  function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    confettis.forEach((confetti, index) => {
      confetti.update();
      confetti.draw();
      if (confetti.y > canvas.height) {
        confettis.splice(index, 1);
      }
    });
    if (confettis.length > 0) {
      requestAnimationFrame(animate);
    }
  }
  confettiButton.addEventListener("click", () => {
    createConfettis();
    animate();
  });
  window.addEventListener("resize", () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  });

Conclusion

This is a simple confetti animation that you can recreate with Tailwind CSS and JavaScript. You can customize the colors, number of confettis, gravity, terminal velocity, and drag to your liking.

Hope you enjoyed this tutorial and have a good day!

/Michael Andreuzza

Did you like this tutorial? Please share it with your friends!

Unlock all themes for $199 for forever! Includes lifetime updates, new themes, unlimited projects, and support. No subscription needed.

— No subscription required!