-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfetti.tsx
executable file
·76 lines (62 loc) · 1.87 KB
/
confetti.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { randomRange } from "./util";
interface ConfettiFragment {
position: { x: number; y: number };
angle: number;
life: number;
maxLife: number;
speed: number;
color: string;
}
const colors = [
"green",
"red",
"yellow",
"orange",
"pink",
"purple",
"blue",
"lightblue",
];
export function spawnConfetti(x: number, y: number) {
const size = 200;
const canvas = document.createElement("canvas");
canvas.style.position = "absolute";
canvas.style.top = `${y - size / 2}px`;
canvas.style.left = `${x - size / 2}px`;
canvas.width = size;
canvas.height = size;
const center = { x: canvas.width / 2, y: canvas.height / 2 };
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
let confetti: (ConfettiFragment | null)[] = [];
let amount = randomRange(50, 100);
for (let i = 0; i !== amount; i++) {
confetti.push({
position: { ...center },
angle: randomRange(0, 360),
life: 0,
maxLife: randomRange(15, 40),
speed: randomRange(1, 5),
color: colors[Math.floor(Math.random() * colors.length)],
});
}
let interval = setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const fragment of confetti as ConfettiFragment[]) {
ctx.fillStyle = fragment.color;
ctx.fillRect(fragment.position.x, fragment.position.y, 5, 5);
const rad = (fragment.angle * Math.PI) / 180;
fragment.position.x += Math.cos(rad) * fragment.speed;
fragment.position.y += Math.sin(rad) * fragment.speed;
fragment.life++;
fragment.life++;
if (fragment.life > fragment.maxLife)
confetti[confetti.indexOf(fragment)] = null;
}
confetti = confetti.filter((x) => x !== null);
if (confetti.length === 0) {
clearInterval(interval);
document.body.removeChild(canvas);
}
}, 1000 / 60);
document.body.appendChild(canvas);
}