HomeCanvasConfetti Effect Javascript

Confetti Effect Javascript

Hey everyone. Welcome to today’s tutorial. First of all, I would like to thank all of you for the 50,000 subscribers on my YouTube channel. Heartly thankful for all the love and support you have been constantly pouring on me and my work. This code is going to be a celebration code. We will learn how to create the falling confetti effect. To build this effect, we need HTML, CSS, and JavaScript.

This is an intermediate to expert-level JavaScript project. I would suggest beginners try some other tutorials before they try this one. I have explained each step in JavaScript code with comments.

If you are interested to learn more about such JavaScript projects, you can check out this playlist here. This playlist consists of about a hundred-plus tutorials that will help you enhance your JavaScript skills. The difficulty level of this project varies from easy to quite complex, and this playlist is suitable for all kinds of JavaScript learning is beginners to experts.

Video Tutorial:

If you are interested to learn through video tutorials instead of reading this blog post, you can check out the video down below. Also. subscribe to my YouTube channel where I post new tips, tricks and tutorials every alternate day.

 

Project Folder Structure:

Before we start coding, let us take a look at the project folder structure. Create a project folder called confetti effect. Inside this folder, we have 3 files. These files are indexe.html style.css script.js. The first file is the HTML document, the next one is the style sheet, and the last one is the script file.

HTML:

You begin with the HTML code. Now copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Confetti Effect</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="text">
      <h1>
        50K <br />
        SUBSCRIBERS
      </h1>
      <h3>THANK YOU EVERYONE</h3>
    </div>
    <canvas id="canvas"></canvas>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style this code using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  box-sizing: border-box;
}
body {
  padding: 0;
  margin: 0;
  overflow: hidden;
  background-color: #13033f;
}
.text {
  font-family: "Poppins", sans-serif;
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  color: #ffffff;
  text-align: center;
  letter-spacing: 0.2em;
}
h1 {
  font-size: 3em;
  font-weight: 600;
}
h3 {
  font-weight: 400;
}

Javascript:

Lastly, we implement the functionality using JavaScript.
We do this in the following steps:
Create initial references
Request animation frame
Create a function that generates a random number
Create a function that creates confetti particles
Display confetti on the screen
Specify particle and particle features
Specify methods associated with the particle
Functions on Window load

let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let width = window.innerWidth;
let height = window.innerHeight;
let particles = [];
let particleSettings = {
  count: 500,
  gravity: 0.05,
  wave: 0,
};

window.requestAnimationFrame =
  window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequesAnimationFrame ||
  window.oRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  function (callback) {
    window.setTimeout(callback, 1000 / 60);
  };

//random number between range
function randomNumberGenerator(min, max) {
  return Math.random() * (max - min) + min;
}

//Creates Confetti (particles)
function createConfetti() {
  while (particles.length < particleSettings.count) {
    let particle = new Particle();

    //Random colors
    particle.color = `rgb( ${randomNumberGenerator(
      0,
      255
    )}, ${randomNumberGenerator(0, 255)}, ${randomNumberGenerator(0, 255)}`;
    //Store particles
    particles.push(particle);
  }
}

//Starts the confetti
const startConfetti = () => {
  context.clearRect(0, 0, window.innerWidth, window.innerHeight);
  createConfetti();
  for (let i in particles) {
    //Movement and shaking efffect
    particleSettings.wave += 0.4;
    particles[i].tiltAngle += randomNumberGenerator(0.01, 2);
    particles[i].y +=
      (Math.sin(particleSettings.wave) +
        particles[i].area +
        particleSettings.gravity) *
      0.2;
    particles[i].tilt = Math.cos(particles[i].tiltAngle) * 0.3;
    //Draw the particle on screen
    particles[i].draw();
    //if particle has crosses the screen height
    if (particles[i].y > height) {
      particles[i] = new Particle();
      //Random colors
      particles[i].color = `rgb( ${randomNumberGenerator(
        0,
        255
      )}, ${randomNumberGenerator(0, 255)}, ${randomNumberGenerator(0, 255)}`;
    }
  }
  animationTimer = requestAnimationFrame(startConfetti);
};

function Particle() {
  this.x = Math.random() * width;
  this.y = Math.random() * height - height;
  this.area = randomNumberGenerator(10, 15);
  this.tilt = randomNumberGenerator(-4, 4);
  this.tiltAngle = 0;
}

//Mathod associated with particle
Particle.prototype = {
  draw: function () {
    context.beginPath();
    context.lineWidth = this.area;
    context.strokeStyle = this.color;
    this.x = this.x + this.tilt;
    context.moveTo(this.x + this.area / 2, this.y);
    context.lineTo(this.x, this.y + this.tilt + this.area / 2);
    context.stroke();
  },
};

window.onload = () => {
  canvas.width = width;
  canvas.height = height;
  window.requestAnimationFrame(startConfetti);
};

That’s it for this tutorial. If you face any difficulties while creating this project, you can download the source code by clicking on the download button below. Also, if you have any queries, suggestions or feedback you can comment on them below.
Happy Coding!

Previous articleMCQ – 28/11/22
Next articleMCQ – 30/11/22
RELATED ARTICLES

1 COMMENT

  1. Hello Mitali!!!

    I have just discovered your Youtube channel and come by to say thanks to you. Your videos are very useful and clear and i learn a lot with them.

    I am trying to replicated the Confetti effect into my react/typescript project and I am straggling a little as I am not able to make the particle ‘fall’.

    Anyway, thank you much

LEAVE A REPLY

Please enter your comment!
Please enter your name here

eighteen − nine =

Most Popular