-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
708 lines (612 loc) · 23.2 KB
/
Copy pathscript.js
File metadata and controls
708 lines (612 loc) · 23.2 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// ============================================
// Live viewport height fix (handles mobile address bar show/hide)
// dvh alone doesn't always react live during the animation of the
// browser chrome collapsing/expanding on scroll — this keeps a CSS
// var in sync with the actual visible height at all times.
// ============================================
function setViewportHeight() {
const vh = (window.visualViewport ? window.visualViewport.height : window.innerHeight) * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
}
setViewportHeight();
window.addEventListener('resize', setViewportHeight);
window.addEventListener('orientationchange', setViewportHeight);
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', setViewportHeight);
window.visualViewport.addEventListener('scroll', setViewportHeight);
}
// ============================================
// Balloon colors — curated jewel-tone palette, assigned randomly
// per balloon so they don't all match the active theme accent
// ============================================
const BALLOON_PALETTE = [
{ soft: '#e2c583', mid: '#c9a24b', deep: '#8a6a28' }, // gold
{ soft: '#eab7c1', mid: '#d98a9a', deep: '#93505d' }, // rose
{ soft: '#7fb3dd', mid: '#4d8fc4', deep: '#2c5878' }, // sapphire
{ soft: '#7dc0a0', mid: '#4f9d74', deep: '#2f6248' }, // emerald
{ soft: '#ae94db', mid: '#8b6bc4', deep: '#56417a' }, // amethyst
{ soft: '#e0a066', mid: '#c97a3f', deep: '#824d24' }, // copper
{ soft: '#dd8aa3', mid: '#c4587a', deep: '#7c344c' }, // ruby
{ soft: '#c69bf0', mid: '#a06be0', deep: '#5f3a8c' } // violet
];
function assignBalloonColors() {
const shuffled = [...BALLOON_PALETTE].sort(() => Math.random() - 0.5);
document.querySelectorAll('.balloon').forEach((balloon, i) => {
const c = shuffled[i % shuffled.length];
balloon.style.setProperty('--balloon-color-soft', c.soft);
balloon.style.setProperty('--balloon-color', c.mid);
balloon.style.setProperty('--balloon-color-deep', c.deep);
});
}
// ============================================
// Pop sound — plays balloon-pop.mp3 via a pool of <audio> elements
// (so rapid taps can overlap). Falls back to a synthesized tone if
// the file is missing, fails to load, or can't play for any reason.
// Uses <audio>.play() instead of fetch()+decodeAudioData because
// fetch() is blocked by the browser when a page is opened directly
// as a local file:// URL, and this project needs to work both when
// double-clicked locally and when hosted (GitHub Pages, Vercel, etc).
// ============================================
const POP_AUDIO_POOL_SIZE = 5;
let popAudioPool = [];
let popAudioIndex = 0;
let popAudioReady = false;
let popAudioFailed = false;
let audioCtx = null;
function initPopAudioPool() {
if (popAudioPool.length) return;
for (let i = 0; i < POP_AUDIO_POOL_SIZE; i++) {
const audio = new Audio('balloon-pop.mp3');
audio.preload = 'auto';
audio.volume = 0.85;
audio.addEventListener('canplaythrough', () => { popAudioReady = true; }, { once: true });
audio.addEventListener('error', () => { popAudioFailed = true; }, { once: true });
popAudioPool.push(audio);
}
}
function getAudioContext() {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (audioCtx.state === 'suspended') audioCtx.resume();
return audioCtx;
}
function playPopSound() {
if (!popAudioFailed && popAudioPool.length) {
try {
const audio = popAudioPool[popAudioIndex];
popAudioIndex = (popAudioIndex + 1) % popAudioPool.length;
audio.currentTime = 0;
audio.playbackRate = 0.94 + Math.random() * 0.12;
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.catch(() => {
// playback blocked or file genuinely missing — use synth fallback this time
try { playSynthPopSound(getAudioContext()); } catch (e) {}
});
}
return;
} catch (e) {
// fall through to synth
}
}
try { playSynthPopSound(getAudioContext()); } catch (e) {}
}
function playSynthPopSound(ctx) {
try {
const now = ctx.currentTime;
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = 'triangle';
osc.frequency.setValueAtTime(620, now);
osc.frequency.exponentialRampToValueAtTime(140, now + 0.09);
gain.gain.setValueAtTime(0.0001, now);
gain.gain.exponentialRampToValueAtTime(0.35, now + 0.008);
gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.14);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(now);
osc.stop(now + 0.15);
// brief noise burst layered on top for a crisper "snap"
const bufferSize = ctx.sampleRate * 0.05;
const noiseBuffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
const data = noiseBuffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = (Math.random() * 2 - 1) * (1 - i / bufferSize);
}
const noise = ctx.createBufferSource();
noise.buffer = noiseBuffer;
const noiseGain = ctx.createGain();
noiseGain.gain.setValueAtTime(0.18, now);
noiseGain.gain.exponentialRampToValueAtTime(0.0001, now + 0.05);
noise.connect(noiseGain);
noiseGain.connect(ctx.destination);
noise.start(now);
} catch (e) {
// Web Audio unavailable — fail silently, popping still works visually
}
}
// ============================================
// Poppable balloons
// ============================================
function popBalloon(balloonEl) {
if (balloonEl.classList.contains('popped')) return;
balloonEl.classList.add('popped');
playPopSound();
const bodyEl = balloonEl.querySelector('.balloon-body') || balloonEl;
const rect = bodyEl.getBoundingClientRect();
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
const balloonColor = balloonEl.style.getPropertyValue('--balloon-color') || '';
spawnPopShards(cx, cy, balloonColor);
setTimeout(() => {
balloonEl.classList.remove('popped');
balloonEl.classList.add('reset-position');
requestAnimationFrame(() => balloonEl.classList.remove('reset-position'));
}, 500);
}
function spawnPopShards(x, y, colorVar) {
const shardCount = 10;
for (let i = 0; i < shardCount; i++) {
const angle = (Math.PI * 2 * i) / shardCount + Math.random() * 0.4;
const speed = Math.random() * 5 + 3.5;
popShards.push({
x, y,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed - 1.5,
width: Math.random() * 5 + 5,
height: Math.random() * 9 + 7,
curve: (Math.random() - 0.5) * 8,
rotation: Math.random() * 360,
rotationSpeed: (Math.random() - 0.5) * 22,
life: 1,
color: colorVar || confettiColorPalette[Math.floor(Math.random() * confettiColorPalette.length)]
});
}
}
function setupBalloonInteractions() {
document.querySelectorAll('.balloon').forEach(balloon => {
balloon.addEventListener('click', () => popBalloon(balloon));
balloon.addEventListener('touchstart', (e) => { e.preventDefault(); popBalloon(balloon); }, { passive: false });
balloon.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); popBalloon(balloon); }
});
});
}
let WISHES = [];
let currentLanguage = 'en';
let currentTheme = 'classic';
let celebrationData = { name: '', age: null, theme: 'classic', language: 'en' };
let currentWishIndex = 0;
let wishInterval = null;
let isMusicPlaying = false;
const elements = {
customizationPanel: document.getElementById('customization-panel'),
celebrationContent: document.getElementById('celebration-content'),
nameInput: document.getElementById('name-input'),
ageInput: document.getElementById('age-input'),
themeSelect: document.getElementById('theme-select'),
languageSelect: document.getElementById('language-select'),
startBtn: document.getElementById('start-celebration'),
birthdayName: document.getElementById('birthday-name'),
ageCounter: document.getElementById('age-counter'),
rotatingWish: document.getElementById('rotating-wish'),
replayBtn: document.getElementById('replay-btn'),
customizeBtn: document.getElementById('customize-btn'),
shareBtn: document.getElementById('share-btn'),
musicToggle: document.getElementById('music-toggle'),
confettiCanvas: document.getElementById('confetti-canvas'),
birthdayMusic: document.getElementById('birthday-music'),
toast: document.getElementById('toast')
};
// ============================================
// Obfuscated share token
// A lightweight XOR + base64 scramble so the URL doesn't show
// plain "?name=X&age=Y" query params. This is obfuscation, not
// real encryption — anyone determined could decode it — but it
// keeps the payload unreadable at a glance and out of browser
// history/analytics as plain text. True tamper-proof secrecy
// would need a backend, which this static site doesn't have.
// ============================================
const TOKEN_KEY = 'hbday-2024';
function xorString(str, key) {
let out = '';
for (let i = 0; i < str.length; i++) {
out += String.fromCharCode(str.charCodeAt(i) ^ key.charCodeAt(i % key.length));
}
return out;
}
function encodeToken(data) {
const payload = JSON.stringify(data);
const scrambled = xorString(payload, TOKEN_KEY);
// btoa needs a binary string; encodeURIComponent/unescape bridges UTF-8 safely
const b64 = btoa(unescape(encodeURIComponent(scrambled)));
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function decodeToken(token) {
try {
let b64 = token.replace(/-/g, '+').replace(/_/g, '/');
while (b64.length % 4) b64 += '=';
const scrambled = decodeURIComponent(escape(atob(b64)));
const payload = xorString(scrambled, TOKEN_KEY);
return JSON.parse(payload);
} catch (e) {
return null;
}
}
function getURLParameters() {
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('c');
if (token) {
const data = decodeToken(token);
if (data) {
return {
name: data.n ? String(data.n).trim() : null,
age: data.a ? parseInt(data.a, 10) : null,
theme: data.t || null,
language: data.l || null
};
}
}
return { name: null, age: null, theme: null, language: null };
}
function buildShareURL(name, age, theme, language) {
const token = encodeToken({ n: name, a: age, t: theme, l: language });
const url = new URL(window.location.origin + window.location.pathname);
url.searchParams.set('c', token);
return url.toString();
}
function updateURL(name, age, theme, language) {
const url = new URL(buildShareURL(name, age, theme, language));
window.history.pushState({}, '', url);
}
// ============================================
// Internationalization (i18n)
// ============================================
function applyTranslations(lang) {
if (!translations[lang]) lang = 'en';
const trans = translations[lang];
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
if (trans[key]) el.textContent = trans[key];
});
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
const key = el.getAttribute('data-i18n-placeholder');
if (trans[key]) el.placeholder = trans[key];
});
WISHES = trans.wishes || translations.en.wishes;
document.body.setAttribute('dir', (lang === 'ar' || lang === 'ur') ? 'rtl' : 'ltr');
currentLanguage = lang;
}
function applyTheme(theme) {
document.body.setAttribute('data-theme', theme);
currentTheme = theme;
}
// ============================================
// Initialization
// ============================================
function init() {
applyTranslations('en');
applyTheme('classic');
const urlData = getURLParameters();
if (urlData.language && translations[urlData.language]) {
applyTranslations(urlData.language);
elements.languageSelect.value = urlData.language;
}
if (urlData.theme) {
applyTheme(urlData.theme);
elements.themeSelect.value = urlData.theme;
}
if (urlData.name && urlData.age) {
celebrationData.name = urlData.name;
celebrationData.age = urlData.age;
celebrationData.theme = urlData.theme || 'classic';
celebrationData.language = urlData.language || 'en';
startCelebration();
} else {
showCustomizationPanel();
}
setupEventListeners();
setupCanvas();
setupBalloonInteractions();
startSceneLoop();
}
function setupEventListeners() {
elements.startBtn.addEventListener('click', handleStartCelebration);
elements.nameInput.addEventListener('keypress', e => { if (e.key === 'Enter') handleStartCelebration(); });
elements.ageInput.addEventListener('keypress', e => { if (e.key === 'Enter') handleStartCelebration(); });
elements.themeSelect.addEventListener('change', e => applyTheme(e.target.value));
elements.languageSelect.addEventListener('change', e => applyTranslations(e.target.value));
elements.replayBtn.addEventListener('click', replayCelebration);
elements.customizeBtn.addEventListener('click', showCustomizationPanel);
elements.shareBtn.addEventListener('click', handleShare);
elements.musicToggle.addEventListener('click', toggleMusic);
window.addEventListener('resize', setupCanvas);
}
// ============================================
// Customization Panel
// ============================================
function showCustomizationPanel() {
elements.customizationPanel.classList.remove('hidden');
elements.celebrationContent.classList.add('hidden');
if (celebrationData.name) elements.nameInput.value = celebrationData.name;
if (celebrationData.age) elements.ageInput.value = celebrationData.age;
if (celebrationData.theme) { elements.themeSelect.value = celebrationData.theme; applyTheme(celebrationData.theme); }
if (celebrationData.language) { elements.languageSelect.value = celebrationData.language; applyTranslations(celebrationData.language); }
setTimeout(() => elements.nameInput.focus(), 100);
stopCelebration();
}
function handleStartCelebration() {
getAudioContext();
initPopAudioPool();
const name = elements.nameInput.value.trim();
const age = parseInt(elements.ageInput.value, 10);
const theme = elements.themeSelect.value;
const language = elements.languageSelect.value;
if (!name) {
elements.nameInput.focus();
showToast(translations[currentLanguage]?.['toast-name-required'] || 'Please enter a name');
return;
}
if (!age || age < 1 || age > 150) {
elements.ageInput.focus();
showToast(translations[currentLanguage]?.['toast-age-required'] || 'Please enter a valid age');
return;
}
celebrationData = { name, age, theme, language };
updateURL(name, age, theme, language);
startCelebration();
}
function startCelebration() {
elements.customizationPanel.classList.add('hidden');
elements.celebrationContent.classList.remove('hidden');
applyTheme(celebrationData.theme);
applyTranslations(celebrationData.language);
elements.birthdayName.textContent = celebrationData.name;
elements.ageCounter.textContent = '0';
assignBalloonColors();
setTimeout(() => animateAgeCounter(), 1200);
setTimeout(() => startWishRotation(), 2000);
setTimeout(() => startConfetti(), 300);
attemptMusicAutoplay();
}
function replayCelebration() {
stopCelebration();
requestAnimationFrame(() => startCelebration());
}
function stopCelebration() {
if (wishInterval) { clearInterval(wishInterval); wishInterval = null; }
confettiActive = false;
if (isMusicPlaying) {
elements.birthdayMusic.pause();
elements.birthdayMusic.currentTime = 0;
isMusicPlaying = false;
elements.musicToggle.classList.remove('is-playing');
}
}
// ============================================
// Share
// ============================================
async function handleShare() {
const url = buildShareURL(celebrationData.name, celebrationData.age, celebrationData.theme, celebrationData.language);
try {
if (navigator.share) {
await navigator.share({ title: 'Happy Birthday', url });
return;
}
} catch (e) {
// fall through to clipboard
}
try {
await navigator.clipboard.writeText(url);
showToast(translations[currentLanguage]?.['toast-link-copied'] || 'Link copied to clipboard');
} catch (e) {
showToast(url);
}
}
function showToast(message) {
elements.toast.textContent = message;
elements.toast.classList.add('visible');
clearTimeout(showToast._t);
showToast._t = setTimeout(() => elements.toast.classList.remove('visible'), 2800);
}
// ============================================
// Age Counter Animation
// ============================================
function animateAgeCounter() {
const targetAge = celebrationData.age;
const duration = 1500;
const startTime = Date.now();
function update() {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
const easeProgress = 1 - Math.pow(1 - progress, 3);
const currentValue = Math.floor(easeProgress * targetAge);
elements.ageCounter.textContent = currentValue;
if (progress < 1) requestAnimationFrame(update);
else elements.ageCounter.textContent = targetAge;
}
update();
}
// ============================================
// Rotating Wishes
// ============================================
function startWishRotation() {
currentWishIndex = 0;
showWish();
wishInterval = setInterval(() => {
currentWishIndex = (currentWishIndex + 1) % WISHES.length;
showWish();
}, 4000);
}
function showWish() {
const el = elements.rotatingWish;
el.style.opacity = '0';
el.style.transform = 'translateY(10px)';
setTimeout(() => {
el.textContent = WISHES[currentWishIndex];
el.style.opacity = '1';
el.style.transform = 'translateY(0)';
}, 300);
}
// ============================================
// Music Control
// ============================================
function attemptMusicAutoplay() {
const playPromise = elements.birthdayMusic.play();
if (playPromise !== undefined) {
playPromise
.then(() => { isMusicPlaying = true; elements.musicToggle.classList.add('is-playing'); })
.catch(() => { isMusicPlaying = false; elements.musicToggle.classList.remove('is-playing'); });
}
}
function toggleMusic() {
if (isMusicPlaying) {
elements.birthdayMusic.pause();
isMusicPlaying = false;
elements.musicToggle.classList.remove('is-playing');
} else {
elements.birthdayMusic.play();
isMusicPlaying = true;
elements.musicToggle.classList.add('is-playing');
}
}
// ============================================
// Confetti Animation (Canvas) — mixed particle shapes
// ============================================
let confettiParticles = [];
function themeConfettiColors() {
const styles = getComputedStyle(document.body);
const accent = styles.getPropertyValue('--accent').trim() || '#c9a24b';
const soft = styles.getPropertyValue('--accent-soft').trim() || '#e2c583';
const deep = styles.getPropertyValue('--accent-deep').trim() || '#8a6a28';
return [accent, soft, deep, '#f3f1ec', 'rgba(243,241,236,0.5)'];
}
class ConfettiParticle {
constructor(canvas) {
this.canvas = canvas;
this.shape = ['rect', 'circle', 'streamer'][Math.floor(Math.random() * 3)];
this.reset();
this.y = Math.random() * canvas.height;
}
reset() {
this.x = Math.random() * this.canvas.width;
this.y = -20;
this.size = Math.random() * 7 + 4;
this.speedY = Math.random() * 2.2 + 1.3;
this.speedX = Math.random() * 1.6 - 0.8;
this.color = confettiColorPalette[Math.floor(Math.random() * confettiColorPalette.length)];
this.rotation = Math.random() * 360;
this.rotationSpeed = Math.random() * 6 - 3;
this.opacity = Math.random() * 0.4 + 0.5;
this.sway = Math.random() * 0.02 + 0.01;
this.swayOffset = Math.random() * Math.PI * 2;
}
update(t) {
this.y += this.speedY;
this.x += this.speedX + Math.sin(t * this.sway + this.swayOffset) * 0.6;
this.rotation += this.rotationSpeed;
if (this.y > this.canvas.height + 20) this.reset();
if (this.x < -20) this.x = this.canvas.width + 20;
if (this.x > this.canvas.width + 20) this.x = -20;
}
draw(ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation * Math.PI / 180);
ctx.globalAlpha = this.opacity;
ctx.fillStyle = this.color;
if (this.shape === 'rect') {
ctx.fillRect(-this.size / 2, -this.size / 2, this.size, this.size / 2.2);
} else if (this.shape === 'circle') {
ctx.beginPath();
ctx.arc(0, 0, this.size / 2.4, 0, Math.PI * 2);
ctx.fill();
} else {
ctx.fillRect(-this.size / 6, -this.size, this.size / 3, this.size * 2);
}
ctx.restore();
}
}
let confettiColorPalette = ['#c9a24b'];
let popShards = [];
let confettiActive = false;
function setupCanvas() {
const canvas = elements.confettiCanvas;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function startConfetti() {
const canvas = elements.confettiCanvas;
const ctx = canvas.getContext('2d');
confettiColorPalette = themeConfettiColors();
confettiParticles = [];
const particleCount = Math.min(110, Math.floor(window.innerWidth / 12));
for (let i = 0; i < particleCount; i++) confettiParticles.push(new ConfettiParticle(canvas));
confettiActive = true;
}
// Single persistent render loop shared by confetti and pop shards.
// Runs from page load onward so balloons stay poppable — and shards
// still render — even if confetti hasn't started yet or was stopped.
let sceneAnimationId = null;
function startSceneLoop() {
const canvas = elements.confettiCanvas;
const ctx = canvas.getContext('2d');
let t = 0;
function loop() {
t += 1;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (confettiActive) {
confettiParticles.forEach(p => { p.update(t); p.draw(ctx); });
}
drawPopShards(ctx);
sceneAnimationId = requestAnimationFrame(loop);
}
loop();
}
function drawPopShards(ctx) {
if (popShards.length === 0) return;
ctx.save();
popShards.forEach(s => {
s.x += s.vx;
s.y += s.vy;
s.vy += 0.18;
s.vx *= 0.99;
s.rotation += s.rotationSpeed;
s.life -= 0.022;
if (s.life > 0) {
ctx.save();
ctx.globalAlpha = Math.max(s.life, 0);
ctx.translate(s.x, s.y);
ctx.rotate(s.rotation * Math.PI / 180);
ctx.fillStyle = s.color;
// torn rubber-scrap shape: curved quad, not a clean geometric piece
const w = s.width;
const h = s.height;
ctx.beginPath();
ctx.moveTo(0, -h / 2);
ctx.quadraticCurveTo(w / 2 + s.curve, -h / 4, w / 2, h / 2);
ctx.quadraticCurveTo(s.curve, h / 2 + 2, -w / 2, h / 3);
ctx.quadraticCurveTo(-w / 2 - s.curve, 0, 0, -h / 2);
ctx.closePath();
ctx.fill();
// subtle inner highlight so pieces still read as glossy balloon rubber
ctx.globalAlpha = Math.max(s.life, 0) * 0.35;
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.beginPath();
ctx.ellipse(-w / 6, -h / 6, w / 5, h / 5, 0, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
});
ctx.restore();
popShards = popShards.filter(s => s.life > 0);
}
// ============================================
// Start Application
// ============================================
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}