I’m a simple chick: sparklers and fireworks just make me plain happy. š Want to add a celebratory element to your Angular project? Today we’ll accomplish that by coming back to an old favorite: Canvas Confetti. Keep reading to find out how!
Procedure
As in previous tutorials, letās first install Node and npm:
- Node: https://nodejs.org/
- npm: https://www.npmjs.com/
Set up the Angular project by installing the Angular CLI tool:
npm install -g @angular/cli
Create a project called my-fireworks-project:
ng new my-fireworks-project
Enter the project directory:
cd my-fireworks-project
Install canvas-confetti:
npm install --save canvas-confetti
Install the Types if using TypeScript:
npm i --save-dev @types/canvas-confetti
Now here is the code to achieve continuous fireworks with a duration of 15 seconds:
app.ts
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import confetti from 'canvas-confetti';
@Component({
selector: 'app-root',
imports: [CommonModule],
templateUrl: './app.html',
styleUrl: './app.css'
})
export class App {
duration = 15 * 1000;
animationEnd = Date.now() + this.duration;
defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 0 };
public randomInRange(min, max) {
return Math.random() * (max - min) + min;
}
public interval = setInterval(() => {
let timeLeft = this.animationEnd - Date.now();
if (timeLeft <= 0) {
return clearInterval(this.interval);
}
var particleCount = 50 * (timeLeft / this.duration);
confetti({ ...this.defaults, particleCount, origin: { x: this.randomInRange(0.1, 0.3), y: Math.random() - 0.2 } });
confetti({ ...this.defaults, particleCount, origin: { x: this.randomInRange(0.7, 0.9), y: Math.random() - 0.2 } });
}, 250);
}
Check your browser at localhost:4200 for the result! š
Conclusion
We have successfully created a fireworks effect in our Angular project. Hopefully this will make your day a little more glitzy. š Happy Coding!
