HomeJavascriptCanvasConfetti on button click with javascript

Confetti on button click with javascript

Introduction:

Are you looking to add a fun and interactive element to your website? Confetti animations can be a great way to engage your users and celebrate special moments. In this tutorial, we will walk you through the process of creating a confetti animation using HTML, CSS, and JavaScript.

Things You Will Learn:

By following this tutorial, you will learn how to create an interactive confetti animation on your web page. We will cover the following topics:

  1. Setting up the project folder structure.
  2. Writing HTML to create the necessary elements.
  3. Styling the confetti using CSS.
  4. Implementing the confetti animation with JavaScript.
  5. Detecting user interactions (mouse click or touch) to trigger the animation.

Video Tutorial:

Here is the video tutorial for this project. If you like the tutorial subscribe to my YouTube channel. I post new projects based on HTML, CSS, and Javascript on my channel regularly.

Project Folder Structure:

Let us explore the project folder structure. The project folder consists of 3 files. The HTML file creates the elements required to build the structure and layout of our project. Next, the CSS file styles the elements that we have created with CSS. Finally, Javascript adds functionality to our project. The files used are:

  • index.html
  • style.css
  • script.js

HTML:

We begin with the HTML code. 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 On Button Click</title>
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <canvas id="canvas">Canvas is not supported in your browser</canvas>
    </div>
    <button id="display-confetti">Click Me!</button>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

 

CSS:

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

body {
  overflow: hidden;
}
canvas {
  background-color: #ffffff;
}
button {
  font-size: 1em;
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  padding: 1.5em 3em;
  border-radius: 3em;
  background-color: #1164f4;
  color: #ffffff;
  border: none;
  cursor: pointer;
  font-family: "Poppins", sans-serif;
}

 

JS:

Finally, we add functionality using Javascript. For this once again copy the code below and paste it into your script file.

let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let width = window.innerWidth;
let height = window.innerHeight;
let clicked = false;
let displayButton = document.getElementById("display-confetti");
let particles = [];
let colors = ["#141b41", "306bac", "#6f9ceb", "#98b9f2", "#918ef4"];

//Events object
let events = {
  mouse: {
    down: "mousedown",
    move: "mousemove",
    up: "mouseup",
  },
  touch: {
    down: "touchstart",
    move: "touchmovve",
    up: "touchend",
  },
};

let deviceType = "";
//Detect touch device
const isTouchDevice = () => {
  try {
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};

//For using request animationFrame on all browsers
window.requestAnimationFrame =
  window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequesetAnimationFrame ||
  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;
}

function startConfetti() {
  let current = [];
  context.fillStyle = "rgba(255,255,255,1)";
  context.fillRect(0, 0, width, height);
  if (clicked) {
    createConfetti();
  }
  for (let i in particles) {
    particles[i].draw();
    if (particles[i].move()) {
      current.push(particles[i]);
    }
  }

  particles = current;
  window.requestAnimationFrame(startConfetti);
}

function createConfetti() {
  //Increase range for bigger confetti;
  let numberOfParticles = randomNumberGenerator(10, 20);
  let color = colors[Math.floor(randomNumberGenerator(0, colors.length))];
  for (let i = 0; i < numberOfParticles; i++) {
    let particle = new Particle();
    particle.color = color;
    particles.push(particle);
  }
}

function Particle() {
  let buttonBounds = displayButton.getBoundingClientRect();
  this.width = randomNumberGenerator(0.1, 0.9) * 5;
  this.height = randomNumberGenerator(0.1, 0.9) * 5;
  this.x = buttonBounds.x + buttonBounds.width / 2;
  this.y = buttonBounds.y + buttonBounds.height / 2;
  let angle = Math.random() * Math.PI * 2;
  let speed = randomNumberGenerator(1, 5);
  this.vx = Math.cos(angle) * speed;
  this.vy = Math.sin(angle) * speed;
}

Particle.prototype = {
  move: function () {
    if (this.x >= canvas.width || this.y >= canvas.height) {
      return false;
    }
    return true;
  },
  draw: function () {
    this.x += this.vx;
    this.y += this.vy;
    context.save();
    context.beginPath();
    context.translate(this.x, this.y);
    context.arc(0, 0, this.width, 0, Math.PI * 2);
    context.fillStyle = this.color;
    context.closePath();
    context.fill();
    context.restore();
  },
};

isTouchDevice();
displayButton.addEventListener(events[deviceType].down, function (e) {
  e.preventDefault();
  clicked = true;
});

displayButton.addEventListener(events[deviceType].up, function (e) {
  e.preventDefault();
  clicked = false;
});

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

 

Conclusion:

Congratulations! You’ve successfully created a confetti animation using HTML, CSS, and JavaScript. This interactive element can be a fun addition to your website, especially for celebrations and special occasions. Feel free to customize the colors, sizes, and behavior of the confetti to match your website’s theme.

Previous articleMultiple Dice Roller
Next articleCSS Art for beginners
RELATED ARTICLES

Bear CSS Art

Elephant CSS Art

LEAVE A REPLY

Please enter your comment!
Please enter your name here

12 − 4 =

Most Popular