Confetti Shooter Script html css and js

Experience the vibrant confetti shooter animation with interactive design and party popper effects. Perfect for celebrations and fun!

the Confetti Shooter Script for Raj Logic Tech

Party popper confetti shooter animation with vibrant colors and interactive design

Introduction

The Confetti Shooter is a fun and engaging way to add interactive animation to your web applications. This project, developed by Raj Logic Tech, demonstrates how to shoot confetti particles on mouse click using a combination of HTML, CSS, and JavaScript. Below is a detailed breakdown of how this implementation works, explaining every part of the code in depth to ensure a complete understanding of the logic and techniques used.

HTML Structure

The HTML file lays the foundation for the confetti animation by using simple and minimal markup elements. These elements serve as containers for the interactive confetti shooter.

<canvas id="canvas"></canvas>

<div class="intro" id="intro">
    Get the Party Started.
</div>

<div id="shaker">
    <div class="tada" id="tada">
        <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/62921/party-popper.png" alt="" />
    </div>
</div>

The key elements in this structure are:

  • Canvas: The <canvas> element is crucial as it serves as the area where the confetti particles are drawn.
  • Intro Section: The <div id="intro"> provides a simple message, "Get the Party Started," prompting user interaction.
  • Shaker Element: This div contains the confetti icon (in this case, an image of a party popper) inside a <div id="tada">. When the user interacts with the canvas, the party popper will appear to shake, enhancing the visual effect.

CSS Styling (style.scss)

The styling ensures that the elements look polished, providing both aesthetic value and alignment with the animations triggered through JavaScript. The .scss (Sass) file further organizes the CSS and enables easy customization through variables and nested rules.

JavaScript Logic (script.js)

Now, let’s break down the JavaScript file to understand the logic behind the confetti shooting animation. This is where the bulk of the magic happens.

Functions and Event Handlers

getDegAngle Function

function getDegAngle(x0, y0, x1, y1) {
  const y = y1 - y0;
  const x = x1 - x0;
  return Math.atan2(y, x) * (180 / Math.PI);
}

This function calculates the angle between two points (x0, y0) and (x1, y1) in degrees, which is crucial for determining the direction in which the confetti particles will be shot.

addClass and removeClass Functions

function addClass(el, className) {
  el.classList.add(className);
}
function removeClass(el, className) {
  el.classList.remove(className);
}

These utility functions add or remove a class from a DOM element, helping to apply or remove CSS animations dynamically during user interaction.

Variables

Several important variables are declared to control the behavior of the confetti:

const DECAY = 4; // Lifespan of the confetti particles
const SPREAD = 50; // Range of angles in which the confetti spreads
const GRAVITY = 1200; // Simulates the force of gravity on confetti
let angle = 270; // Initial angle of confetti shoot
let shoot = false; // Controls when to shoot confetti

Canvas Setup and Listeners

let dpr = window.devicePixelRatio || 1;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);

function setCanvasSize() {
  canvas.width = window.innerWidth * dpr;
  canvas.height = window.innerHeight * dpr;
}

This section sets the canvas size to match the window dimensions, scaled according to the device's pixel ratio (dpr), ensuring high-resolution rendering of the confetti animation.

function setupListeners() {
  TweenLite.ticker.addEventListener('tick', render); // Keeps the animation running
  canvas.addEventListener('mousedown', handleMousedown);
  canvas.addEventListener('mouseup', handleMouseup);
  canvas.addEventListener('mousemove', handleMousemove);
  canvas.addEventListener('touchstart', handleMousedown);
  canvas.addEventListener('touchend', handleMouseup);
  canvas.addEventListener('touchmove', handleTouchmove);
  canvas.addEventListener('resize', setCanvasSize);
}

These event listeners detect mouse and touch interactions. For example, when the user presses down the mouse or touches the screen, the confetti is triggered to shoot.

Handling Mouse and Touch Movement

function handleMousemove(e) {
  const pointerAngle = getDegAngle(canvas.width / 2, canvas.height * .9, e.clientX * dpr, e.clientY * dpr);
  angle = pointerAngle;
  tada.style.transform = `translateX(0)rotate(${angle + 45}deg)`;
}

As the user moves the mouse or touches the screen, the confetti shooter (party popper) rotates to point in the direction of movement. The getDegAngle function calculates the angle, and CSS transforms are applied to rotate the popper.

Confetti Shooting Logic

function shootConfetti() {
  requestAnimationFrame(shootConfetti);
  if (shoot) {
    addConfettiParticles(10, angle, 5000, canvas.width / 2, canvas.height * .9);
  }
}

This function continuously adds confetti particles when the shoot variable is set to true (i.e., when the mouse is pressed or screen is touched). The addConfettiParticles function generates confetti particles based on the current angle and velocity.

Physics and Animation

function tweenConfettiParticle(id) {
  const minAngle = confettiSprites[id].angle - SPREAD / 2;
  const maxAngle = confettiSprites[id].angle + SPREAD / 2;
  const velocity = _.random(minVelocity, maxVelocity);
  TweenLite.to(confettiSprites[id], DECAY, {
    physics2D: { velocity, angle, gravity, friction },
    onComplete: () => {
      _.pull(confettiSpriteIds, id);
      delete confettiSprites[id];
    }
  });
}

Using TweenLite, each confetti particle is animated with realistic physics. The spread, velocity, and gravity are randomized to create a natural effect. Once the confetti decays (using DECAY), it is removed from the canvas.

Conclusion

The Confetti Shooter project by Raj Logic Tech is a visually delightful example of how interactive animations can be created with JavaScript. The combination of physics-based movement, randomization, and user interaction results in a dynamic and engaging experience.

With this code, developers can easily integrate fun animations into their web pages and adapt the logic for other use cases, such as celebrations, notifications, or interactive games.

CSS Styling Breakdown for the Confetti Shooter

In this section, we will explore the CSS used in the Confetti Shooter project, which plays an essential role in defining the visual aesthetics and animation of the confetti shooter. The styling focuses on ensuring that the canvas and interactive elements look polished and cohesive, contributing to the overall user experience. The styles are written using SCSS (Sass), allowing for better organization and flexibility with features like nesting and variables.

Core Styles for the Confetti Shooter

The following is a breakdown of the key styles used in the project.

1. Global Styles

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body, html {
  height: 100%;
  font-family: 'Arial', sans-serif;
  background-color: #282c34;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  color: #fff;
}

2. Canvas Styling

canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 0;
}

3. Intro Section Styling

.intro {
  font-size: 2rem;
  text-align: center;
  z-index: 1;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  animation: fadeIn 1s ease-in-out;
  transition: opacity 0.3s ease;
}

.intro.bye {
  opacity: 0;
  visibility: hidden;
}

4. Shaker and Party Popper Styling

#shaker {
  position: absolute;
  bottom: 2rem;
  display: flex;
  justify-content: center;
  width: 100%;
  z-index: 2;
}

#tada {
  width: 50px;
  height: 50px;
  animation: pop 0.5s ease;
}

5. Animations

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes pop {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.shake {


  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0% {
    transform: rotate(-10deg);
  }
  50% {
    transform: rotate(10deg);
  }
  100% {
    transform: rotate(-10deg);
  }
}

6. Responsive Design

The project ensures responsiveness by setting the canvas to cover the entire viewport and adjusting positioning based on screen size. Media queries can be added if needed to further customize the appearance on different devices.

@media (max-width: 768px) {
  .intro {
    font-size: 1.5rem;
  }

  #tada {
    width: 40px;
    height: 40px;
  }
}

Conclusion

It is done very carefully to make the Confetti Shooter as visually appealing and user engaging as possible. The flexibility of power in SCSS also offers developers more help in the management of stylesheet hierarchy efficiently and hence to style more intuitively and organize the process. This is where SCSS helps developers write cleaner, maintainable code by using variables, mixins, and nesting capabilities, which greatly streamline the whole process. Careful optimization for styling has been given in this regard to make sure the visually dynamic confetti animation looks fluid and polished enough for a wide range of devices and screen sizes from high-resolution desktop monitors to compact mobile screens. This responsiveness is achieved through media queries and responsive design principles that ensure the confetti shooter looks great on whatever device one chooses. This code builds emphasis on cross-browser compatibility, meaning it'll be compatible with any web browser used for smooth, consistent execution, thus providing every visitor with a great user experience. In addition, SCSS allows designers to incorporate variations and flexibility into the design quite conveniently, and those improvements can be done repeatedly in consideration of changing the user's needs or by the emergence of the new designing trends. Openness makes it very likely to add some fresh creative elements or animations to the confetti effect but with updates that can quickly reach the users without comprising their performance or visuals. Overall, the CSS styling, anchored with SCSS, provides space to an imperative mix of technical wizardry and creative chutzpah leading to a Confetti Shooter that shines both technically as well as aesthetically.

Give coplete code contact me 

إرسال تعليق