-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1075 lines (913 loc) · 46.8 KB
/
script.js
File metadata and controls
1075 lines (913 loc) · 46.8 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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Color configuration - centralized for easy modification
const colorConfig = {
// Initial counter animation colors (referenced in HTML)
initial: {
background: '#ff6161', // Initial background (orangish pink)
counterText: '#ffd037', // Counter text color (yellowish)
// Color changes during counting
transitions: {
count15: {
background: '#ffd037', // Yellow background at count 15
text: '#000000' // Black text at count 15
},
count30: {
background: '#940071', // Purple background at count 30
text: '#ffd037' // Yellow text at count 30
}
}
},
// Stacking rectangles colors (alternating pattern)
stackingRectangles: {
first: '#ff8255', // Orange (every 3n+1)
second: '#67b8ff', // Blue (every 3n+2)
third: '#e5fc64' // Light green (every 3n+3)
},
// Scrolling text phrase colors
phrases: {
first: '#ffdb4d', // Yellow for "สุขสันต์" (phrase 1)
second: '#ff7eb3', // Pink for "วันเกิด" (phrase 2)
third: '#4dffdb' // Cyan for "คับผม!" (phrase 3)
},
// Final birthday message screen
finalMessage: {
// Contrasting text colors based on background
textContrast: {
orange: { // For orange background
first: '#4dffdb', // Cyan
second: '#ff7eb3' // Yellow
},
blue: { // For blue background
first: '#ff7eb3', // Magenta
second: '#67b8ff' // Yellow
},
green: { // For green background
first: '#4dffdb', // Magenta
second: '#ff7eb3' // Cyan
},
fallback: { // Default fallback
first: '#ff7eb3', // Magenta
second: '#67b8ff' // Cyan
}
}
}
};
// Function to create stacking rectangles after main animation
function createStackingRectangles() {
// Create container for rectangles
const container = document.createElement('div');
container.className = 'stacking-container';
document.body.appendChild(container);
// Initialize audio immediately and set it to preload
const bgMusic = new Audio('sounds/hbdremix.mp3');
bgMusic.loop = true;
bgMusic.volume = 0.7; // Set volume to 70%
bgMusic.preload = 'auto';
let audioStarted = false;
// Function to play audio with enhanced autoplay handling
const playBackgroundMusic = () => {
console.log("Attempting to play background music");
// Check if audio is already playing
if (audioStarted) return;
// For mobile, we need to try some tricks to bypass autoplay restrictions
const forcedPlay = () => {
// Try multiple play attempts with short intervals
const playAttempt = setInterval(() => {
const playPromise = bgMusic.play();
if (playPromise !== undefined) {
playPromise.then(() => {
console.log("Audio started successfully");
audioStarted = true;
clearInterval(playAttempt);
}).catch(error => {
console.log("Still trying to autoplay...");
// Keep trying in the interval
});
}
}, 100);
// Stop attempts after 2 seconds
setTimeout(() => {
clearInterval(playAttempt);
// If audio still hasn't started, add a one-time click listener as last resort
if (!audioStarted) {
console.log("Adding click listener as last resort");
const startAudio = () => {
bgMusic.play().then(() => {
audioStarted = true;
console.log("Audio started via user interaction");
}).catch(e => console.log("Failed even with interaction", e));
document.removeEventListener('click', startAudio);
};
document.addEventListener('click', startAudio);
}
}, 2000);
};
// Try to play immediately
bgMusic.play().then(() => {
console.log("Audio started immediately");
audioStarted = true;
}).catch(error => {
console.log("Initial autoplay prevented, trying alternative approach");
// If first attempt fails, try our forced approach
forcedPlay();
});
};
// Calculate screen height
const viewportHeight = window.innerHeight;
// Determine base rectangle height based on screen size
let numberOfDivisions;
if (window.innerWidth <= 480) {
numberOfDivisions = 8;
} else if (window.innerWidth <= 768) {
numberOfDivisions = 5;
} else {
numberOfDivisions = 3;
}
// Use exact division to cover the screen with no gaps
const baseRectHeight = viewportHeight / numberOfDivisions;
const numberOfRectangles = numberOfDivisions;
// Create rectangles with precise heights to ensure exact fit
const rectangles = [];
for (let i = 0; i < numberOfRectangles; i++) {
const rect = document.createElement('div');
rect.className = 'stacking-rectangle';
// Ensure exact height to prevent rounding issues
rect.style.height = `${baseRectHeight}px`;
// Disable any margin/padding that could cause spacing issues
rect.style.margin = '0';
rect.style.padding = '0';
rect.style.boxSizing = 'border-box';
// Apply a custom attribute to identify the color pattern
rect.dataset.colorIndex = i % 3;
rect.style.transform = 'translateY(-100%)';
container.appendChild(rect);
rectangles.push(rect);
}
// Show the container
container.style.display = 'block';
// IMPORTANT: Start playing audio immediately before any animations
playBackgroundMusic();
// Create a small delay before visual animations to give audio a chance to start
setTimeout(() => {
// Start the animation sequence
animateStripe(0);
}, 200); // Short delay to prioritize audio start
// Animate stripes sequentially (top-to-bottom) with a recursive function
function animateStripe(i) {
if (i >= rectangles.length) {
// All stripes have been animated, set up zoom interactions after a delay
setTimeout(setupZoomInteractions, 2000, container, rectangles);
return;
}
setTimeout(() => {
// CRITICAL FIX: Force removal of any interfering transitions first
rectangles[i].style.transition = 'transform 1.2s cubic-bezier(0.25, 1, 0.5, 1)';
// Calculate exact position for perfect alignment
const exactPosition = baseRectHeight * i;
// Apply precise position
rectangles[i].style.transform = `translateY(${exactPosition}px)`;
setTimeout(() => {
addScrollingText(rectangles[i], i, 0);
animateStripe(i + 1);
}, 1200);
}, i === 0 ? 300 : 400);
}
// Function to add scrolling text to each rectangle
function addScrollingText(rectangle, index, additionalDelay) {
// Determine which text to display based on pattern
const textPattern = index % 3;
let text = '';
let phraseClass = '';
switch(textPattern) {
case 0:
text = 'สุขสันต์';
phraseClass = 'text-phrase-1';
break;
case 1:
text = 'วันเกิด';
phraseClass = 'text-phrase-2';
break;
case 2:
text = 'คับผม!';
phraseClass = 'text-phrase-3';
break;
}
// Create a single container with different structure
const textContainer = document.createElement('div');
textContainer.className = 'text-scroller';
// Set direction based on index (alternating)
const isRTL = index % 2 === 0;
textContainer.classList.add(isRTL ? 'rtl' : 'ltr');
// Calculate font size based on rectangle height
const fontSize = Math.floor(rectangle.offsetHeight * 0.75);
// Create the text track that will move
const track = document.createElement('div');
track.className = 'text-track';
// Word specific adjustments
let gapMultiplier = 0.75; // Default spacing (reduced to 25% of original 5)
let fontSizeAdjust = 1.0;
if (text === 'วันเกิด') {
gapMultiplier = 0.6; // Reduced to 25% of original 6
fontSizeAdjust = 0.9; // Keep the same size adjustment
} else if (text === 'คับผม!') {
gapMultiplier = 0.6; // Reduced to 25% of original 4
}
// Create content - multiple copies of the text with proper spacing
const viewportWidth = window.innerWidth;
const approxCharWidth = fontSize * 0.6;
const textWidth = text.length * approxCharWidth * fontSizeAdjust;
const repeatsNeeded = Math.ceil(viewportWidth / (textWidth + (approxCharWidth * gapMultiplier))) * 3;
// Create content with proper spacing
for (let i = 0; i < repeatsNeeded; i++) {
const textSpan = document.createElement('span');
textSpan.className = 'scroll-text ' + phraseClass; // Add the phrase-specific class
textSpan.textContent = text;
textSpan.style.fontSize = `${fontSize * fontSizeAdjust}px`;
textSpan.style.marginRight = `${approxCharWidth * gapMultiplier}px`;
// Apply the color directly using the colorConfig
const phrasesColors = [
colorConfig.phrases.first,
colorConfig.phrases.second,
colorConfig.phrases.third
];
textSpan.style.color = phrasesColors[textPattern];
track.appendChild(textSpan);
}
// These two lines were missing - add the elements to the DOM
textContainer.appendChild(track);
rectangle.appendChild(textContainer);
}
}
// Function to set up zoom interaction based on device type
function setupZoomInteractions(container, rectangles) {
// Create a hint element to show users they can interact
const interactionHint = document.createElement('div');
interactionHint.className = 'interaction-hint';
interactionHint.textContent = isMobileDevice() ? 'Tap to zoom' : 'Scroll to zoom';
document.body.appendChild(interactionHint);
// Fade in the hint
setTimeout(() => {
interactionHint.style.opacity = '1';
}, 500);
// Prepare container for zoom effect
container.classList.add('zoom-ready');
// Variables for zoom control
let zoomLevel = 0;
const maxZoomLevel = 1200; // increased max zoom level from 900 to 1200
let isZooming = false;
// Select the middle stripe for focused zooming
const middleIndex = Math.floor(rectangles.length / 2);
const targetStripe = rectangles[middleIndex];
const targetColor = window.getComputedStyle(targetStripe).backgroundColor;
// Make the target stripe stand out slightly - FIXED TIMING
setTimeout(() => {
// IMPORTANT: Only add zoom-target-stripe class once animations are complete
targetStripe.classList.add('zoom-target-stripe');
// Find a suitable text element in the target stripe to zoom into
const textTrack = targetStripe.querySelector('.text-track');
const textElements = textTrack.querySelectorAll('.scroll-text');
// Select an element positioned near the center
let centerTextElement = null;
if (textElements.length > 0) {
// Choose text element near the center of the viewport
const viewportCenter = window.innerWidth / 2;
let closestDistance = Infinity;
textElements.forEach(el => {
const rect = el.getBoundingClientRect();
const distance = Math.abs(rect.left + (rect.width / 2) - viewportCenter);
if (distance < closestDistance) {
closestDistance = distance;
centerTextElement = el;
}
});
// Mark this element for zooming
if (centerTextElement) {
centerTextElement.classList.add('zoom-target-text');
// SIGNIFICANTLY IMPROVED GAP TARGETING:
const text = centerTextElement.textContent;
const rect = centerTextElement.getBoundingClientRect();
const viewportCenter = window.innerWidth / 2;
// Create a temporary span to measure actual character widths
const tempSpan = document.createElement('span');
tempSpan.style.visibility = 'hidden';
tempSpan.style.position = 'absolute';
tempSpan.style.font = window.getComputedStyle(centerTextElement).font;
tempSpan.style.fontSize = window.getComputedStyle(centerTextElement).fontSize;
document.body.appendChild(tempSpan);
// Calculate the actual position of each character and the gap between characters
const charPositions = [];
const gapPositions = [];
let currentOffset = rect.left;
// Add the initial gap at the start of the text
gapPositions.push({
position: currentOffset,
isGap: true,
index: 0,
width: 0
});
// Calculate each character's position and width
for (let i = 0; i < text.length; i++) {
tempSpan.textContent = text.charAt(i);
const charWidth = tempSpan.getBoundingClientRect().width;
charPositions.push({
position: currentOffset,
isGap: false,
char: text.charAt(i),
width: charWidth,
index: i
});
// Calculate the position of the gap after this character
const gapPosition = currentOffset + charWidth;
currentOffset = gapPosition;
gapPositions.push({
position: gapPosition,
isGap: true,
index: i + 1,
width: 0
});
}
// Clean up the temporary element
document.body.removeChild(tempSpan);
// Find the gap that's closest to the viewport center
let closestGap = null;
let minGapDistance = Infinity;
gapPositions.forEach(gap => {
const distance = Math.abs(viewportCenter - gap.position);
if (distance < minGapDistance) {
minGapDistance = distance;
closestGap = gap;
}
});
// Calculate the exact offset needed to position this gap at the viewport center
const fixedOffsetX = viewportCenter - closestGap.position;
// Store these values as data attributes on the element
centerTextElement.dataset.fixedOffsetX = fixedOffsetX.toFixed(2);
centerTextElement.dataset.gapIndex = closestGap.index;
centerTextElement.dataset.gapPosition = closestGap.position.toFixed(2);
// IMPORTANT: Do not set any transform initially to avoid flickering
centerTextElement.style.transform = '';
centerTextElement.style.transition = 'none';
// Store the background color for the final overlay
centerTextElement.dataset.backgroundColor = window.getComputedStyle(targetStripe).backgroundColor;
}
}
}, 1000);
// Detect if this is a mobile device
function isMobileDevice() {
return (typeof window.orientation !== 'undefined') ||
(navigator.userAgent.indexOf('IEMobile') !== -1) ||
(navigator.userAgent.indexOf('Android') !== -1) ||
(navigator.userAgent.indexOf('iPhone') !== -1) ||
(navigator.userAgent.indexOf('iPad') !== -1);
}
// Function to apply zoom effect based on current zoom level
function applyZoom() {
// Remove the hint once zooming starts
if (zoomLevel > 0 && interactionHint.parentNode) {
interactionHint.style.opacity = '0';
setTimeout(() => {
if (interactionHint.parentNode) {
interactionHint.parentNode.removeChild(interactionHint);
}
}, 500);
}
// Add zooming class to body to prevent scrolling
document.body.classList.add('zooming');
// Pause text animations during zoom
rectangles.forEach(rect => {
const textTracks = rect.querySelectorAll('.text-track');
textTracks.forEach(track => {
track.classList.add('paused');
track.style.animationPlayState = 'paused';
});
});
// Store original positions of stripes if not already done
if (!container.dataset.initialized) {
// Store original positions and dimensions
rectangles.forEach((rect, idx) => {
const transform = window.getComputedStyle(rect).transform;
const matrix = new DOMMatrix(transform);
rect.dataset.originalY = matrix.m42;
rect.dataset.originalHeight = rect.offsetHeight;
rect.dataset.index = idx;
// Store original text styles to preserve them
const textElements = rect.querySelectorAll('.scroll-text');
textElements.forEach((text, textIdx) => {
const originalLetterSpacing = window.getComputedStyle(text).letterSpacing;
text.dataset.originalLetterSpacing = originalLetterSpacing;
// Calculate and store fixed positioning data upfront to avoid jitter
if (text.classList.contains('zoom-target-text')) {
// Get initial dimensions and positions once
const rect = text.getBoundingClientRect();
const viewportCenter = window.innerWidth / 2;
// Store the character gap positions once
const gapData = calculateCharacterGaps(text);
// Find the optimal gap position that's closest to viewport center
const optimalGapPosition = findOptimalGapPosition(gapData.gaps, viewportCenter);
// Calculate the fixed offset needed to center this gap
const fixedOffset = viewportCenter - optimalGapPosition;
// Store these fixed values to eliminate recalculation
container.dataset.targetTextInitialLeft = rect.left.toFixed(2);
container.dataset.targetTextInitialWidth = rect.width.toFixed(2);
container.dataset.targetTextFixedOffset = fixedOffset.toFixed(2);
container.dataset.optimalGapPosition = optimalGapPosition.toFixed(2);
}
});
});
container.dataset.initialized = 'true';
}
// Use a smoother non-linear function for zoom acceleration
const zoomProgress = Math.min(1, zoomLevel / maxZoomLevel);
// Use consistent easing with no sudden changes or conditional breakpoints
const acceleratedZoom = Math.pow(zoomProgress, 1.25); // Gentle acceleration
// Apply a consistent scale with extreme final zoom
const sceneScale = 1 + (acceleratedZoom * 45.0);
// Apply the zoom transformation to the container
container.style.transform = `scale(${sceneScale})`;
// Calculate when the target stripe height reaches screen height - but don't use this for conditional logic
const stripeScaledHeight = targetStripe.offsetHeight * sceneScale;
const viewportHeight = window.innerHeight;
// Get the target text element once
const targetElement = document.querySelector('.zoom-target-text');
// Get the fixed offset directly from the element's data attribute and round it
// FIXED: Use a more stable rounding approach
const fixedOffsetX = targetElement ?
Math.round(parseFloat(targetElement.dataset.fixedOffsetX || 0)) : 0;
// FIXED: Apply the exact same transform throughout the zoom process until final z movement
const transformString = `translateX(${fixedOffsetX}px)`;
// FIXED: Only add Z translation at the very end for a smooth transition through text
let finalTransform = transformString;
if (zoomProgress > 0.90) { // Increased threshold to delay z-movement until later
// Use a more dramatic progression for the final push through
const finalZoomProgress = (zoomProgress - 0.90) / 0.10; // Normalize to 0-1 in final 10% of zoom
const zTranslation = Math.floor(15000 * Math.pow(finalZoomProgress, 3)); // Use cubic easing for more dramatic effect
finalTransform = `${transformString} translateZ(${zTranslation}px)`;
}
rectangles.forEach((rect, index) => {
const originalY = parseFloat(rect.dataset.originalY || 0);
rect.style.transform = `translateY(${originalY}px)`;
const textElements = rect.querySelectorAll('.scroll-text');
if (rect.classList.contains('zoom-target-stripe')) {
// Only hide non-target text when we're in the final zoom phase
textElements.forEach(text => {
if (!text.classList.contains('zoom-target-text')) {
// Fade out non-target text with ultra-smooth transition
const fadeProgress = Math.min(1, acceleratedZoom * 1.4);
text.style.opacity = Math.max(0, 1 - fadeProgress);
text.style.display = fadeProgress >= 0.95 ? 'none' : '';
text.style.transform = 'none';
} else {
text.style.display = '';
text.style.opacity = 1;
// Preserve original text color
if (text.classList.contains('text-phrase-1') ||
text.classList.contains('text-phrase-2') ||
text.classList.contains('text-phrase-3')) {
text.style.removeProperty('color');
}
// IMPORTANT: Use consistent easing with no breakpoints or conditionals
// Ultra smooth easing blend with consistent acceleration/deceleration
const easeOutQuint = 1 - Math.pow(1 - zoomProgress, 5);
const easeInOutCubic = zoomProgress < 0.5
? 4 * zoomProgress * zoomProgress * zoomProgress
: 1 - Math.pow(-2 * zoomProgress + 2, 3) / 2;
// Blend easing functions for even smoother transition
const blendedEase = (easeOutQuint * 0.7) + (easeInOutCubic * 0.3);
// Apply Z-translation with consistent formula throughout zoom process
// MUCH deeper z-translation for extreme depth effect
const zTranslation = 12000 * Math.pow(zoomProgress, 2.0);
// CRITICAL: Disable transitions completely to prevent any jitter
text.style.transition = 'none';
// Apply the pre-calculated transform string directly
// This ensures absolutely consistent transforms on every frame
text.style.transform = finalTransform;
text.style.transformOrigin = "center center";
// Force hardware acceleration
text.style.willChange = 'transform';
text.style.backfaceVisibility = 'hidden';
text.style.perspective = '1000px';
}
});
} else {
// Non-target stripes
textElements.forEach(text => {
text.style.display = '';
text.style.transform = 'none';
text.style.opacity = 1;
});
}
// Ensure colors are preserved for all text
textElements.forEach(text => {
text.style.removeProperty('color');
});
});
// Apply consistent perspective changes without any non-linear adjustments
const basePerspective = 1500;
const minPerspective = 80;
// Use a perfectly linear perspective change to avoid any jumps
const perspectiveValue = Math.max(minPerspective, Math.floor(basePerspective - (basePerspective * zoomProgress)));
container.style.perspective = `${perspectiveValue}px`;
// Simple linear overlay transition with no sudden changes
// Start overlay transition MUCH later with longer transition for deeper zoom
if (zoomProgress >= 0.75) { // Start later (from 0.6 to 0.75)
const overlayProgress = Math.min(1, (zoomProgress - 0.75) / 0.25); // Shorter fade (from 0.4 to 0.25)
const overlay = document.getElementById('zoom-overlay') || createOverlay(targetColor);
overlay.style.opacity = overlayProgress;
if (overlayProgress >= 0.8) { // Show message later
showBirthdayMessage();
}
}
}
// Create colored overlay for final transition
function createOverlay(color) {
const overlay = document.createElement('div');
overlay.id = 'zoom-overlay';
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = color;
overlay.style.zIndex = '1000';
overlay.style.opacity = '0';
// Use an even longer, smoother transition for the overlay
overlay.style.transition = 'opacity 4s cubic-bezier(0.1, 0.7, 0.1, 1)';
document.body.appendChild(overlay);
return overlay;
}
// Show final divided screen with typewriter text
function showBirthdayMessage() {
// If we already have the divided screen, don't create another one
if (document.getElementById('divided-screen')) return;
// Get the target stripe color from the overlay
const overlay = document.getElementById('zoom-overlay');
const bgColor = overlay ? overlay.style.backgroundColor : '#000000';
// Determine contrasting text colors with INCREASED CONTRAST
let firstTextColor, secondTextColor;
// Extract RGB components from background color
const rgbMatch = bgColor.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
if (rgbMatch) {
const r = parseInt(rgbMatch[1]);
const g = parseInt(rgbMatch[2]);
const b = parseInt(rgbMatch[3]);
// Use the centralized color config to set message colors based on background
if (r > 200 && g > 100 && b < 130) { // Orange background
firstTextColor = colorConfig.finalMessage.textContrast.orange.first;
secondTextColor = colorConfig.finalMessage.textContrast.orange.second;
} else if (r < 130 && g > 130 && b > 200) { // Blue background
firstTextColor = colorConfig.finalMessage.textContrast.blue.first;
secondTextColor = colorConfig.finalMessage.textContrast.blue.second;
} else if (r > 200 && g > 200 && b < 130) { // Green background
firstTextColor = colorConfig.finalMessage.textContrast.green.first;
secondTextColor = colorConfig.finalMessage.textContrast.green.second;
} else {
// Default fallback with high contrast
firstTextColor = colorConfig.finalMessage.textContrast.fallback.first;
secondTextColor = colorConfig.finalMessage.textContrast.fallback.second;
}
} else {
// Default fallback
firstTextColor = colorConfig.finalMessage.textContrast.fallback.first;
secondTextColor = colorConfig.finalMessage.textContrast.fallback.second;
}
// Create container for divided screen
const dividedScreen = document.createElement('div');
dividedScreen.id = 'divided-screen';
dividedScreen.style.position = 'fixed';
dividedScreen.style.top = '0';
dividedScreen.style.left = '0';
dividedScreen.style.width = '100%';
dividedScreen.style.height = '100%';
dividedScreen.style.zIndex = '1001';
dividedScreen.style.display = 'flex';
dividedScreen.style.flexDirection = 'column';
dividedScreen.style.backgroundColor = bgColor;
dividedScreen.style.opacity = '0';
dividedScreen.style.transition = 'opacity 1s ease';
// Create upper section
const upperSection = document.createElement('div');
upperSection.className = 'screen-section upper-section';
upperSection.style.flex = '1';
upperSection.style.display = 'flex';
upperSection.style.justifyContent = 'center';
upperSection.style.alignItems = 'center';
upperSection.style.padding = '2rem';
upperSection.style.backgroundColor = bgColor;
upperSection.style.position = 'relative';
upperSection.style.zIndex = '2';
// Create lower section
const lowerSection = document.createElement('div');
lowerSection.className = 'screen-section lower-section';
lowerSection.style.flex = '1';
lowerSection.style.display = 'flex';
lowerSection.style.justifyContent = 'center';
lowerSection.style.alignItems = 'center';
lowerSection.style.padding = '2rem';
lowerSection.style.backgroundColor = 'transparent'; // Make transparent to show the rectangle
lowerSection.style.position = 'relative';
lowerSection.style.zIndex = '2';
// Create the expanding rectangle (initially with height 0)
const expandingRect = document.createElement('div');
expandingRect.className = 'expanding-rectangle';
expandingRect.style.position = 'absolute';
expandingRect.style.left = '0';
expandingRect.style.width = '100%';
expandingRect.style.height = '0'; // Start with no height
expandingRect.style.backgroundColor = firstTextColor; // Same as first text color
expandingRect.style.bottom = '0'; // Positioned at the bottom
expandingRect.style.zIndex = '1'; // Below the text
expandingRect.style.transition = 'height 1.2s cubic-bezier(0.25, 1, 0.5, 1)';
expandingRect.style.transformOrigin = 'bottom center'; // Grow upward from bottom
// Prepare text content
const text1 = "ขอให้พ่อสุขภาพร่างกายแข็งแรง มีความสุขในทุกวัน เป็นหัวหน้าครอบครัวที่น่ารักและแสนดีแบบนี้ตลอดไปนะคะ\n-- คุณแม่ --";
const text2 = "ขอให้คุณพ่อมีความสุข มีสุขภาพแข็งแรง อยู่กับพูห์กับคุณแม่ไปนานๆนะคับ (รอเลขนับเกิน 100 อยู่คับ) หมีพูห์ดีใจที่ได้เกิดมาเป็นลูกคุณพ่อคับ\n-- หมีพูห์ --";
// Create fixed size containers with proper contrasting colors
const upperContent = createTypewriterContainer(text1, firstTextColor);
const lowerContent = createTypewriterContainer(text2, secondTextColor);
// Initially hide the lower content
lowerContent.style.opacity = '0';
// Add elements to their containers
upperSection.appendChild(upperContent);
lowerSection.appendChild(lowerContent);
dividedScreen.appendChild(upperSection);
dividedScreen.appendChild(lowerSection);
dividedScreen.appendChild(expandingRect); // Add the expanding rectangle
document.body.appendChild(dividedScreen);
// Animation sequence with proper timing
setTimeout(() => {
// Fade in the main screen
dividedScreen.style.opacity = '1';
// Start typing the first paragraph
startTypewriterAnimation(upperContent, 500, () => {
// After first paragraph completes, animate the rectangle growing downward
setTimeout(() => {
// Expand the rectangle to 50% of the screen height (bottom half)
expandingRect.style.height = '50%';
// After rectangle has expanded, show and animate the second paragraph
setTimeout(() => {
// Fade in the lower content
lowerContent.style.opacity = '1';
// Start typing the second paragraph
startTypewriterAnimation(lowerContent, 0, () => {
// Wait 5 seconds after second paragraph is done, then show image effect
setTimeout(() => {
showPulsingImageEffect();
}, 5000);
});
}, 1200); // Wait for rectangle to finish expanding
}, 500); // Short pause after first paragraph
});
}, 500);
}
// Helper function to create a typewriter container with pre-rendered text
function createTypewriterContainer(text, textColor) {
const container = document.createElement('div');
container.className = 'typewriter-container';
container.style.width = '100%';
container.style.maxWidth = '80%';
container.style.margin = '0 auto';
container.style.textAlign = 'center';
container.style.position = 'relative';
// Create the paragraph
// Create a container for all paragraphs
const textContainer = document.createElement('div');
textContainer.className = 'typewriter-text-container';
textContainer.style.width = '100%';
// Split text by newlines
const lines = text.split('\n');
// Process each line as a separate paragraph
lines.forEach(line => {
const paragraph = document.createElement('p');
paragraph.className = 'typewriter-text';
paragraph.style.fontFamily = "'SaoChingcha', Arial, sans-serif";
paragraph.style.fontSize = 'clamp(1rem, 4vw, 2.5rem)';
paragraph.style.color = textColor;
paragraph.style.textAlign = 'center';
paragraph.style.margin = '0.8em 0'; // Add margin between paragraphs
paragraph.style.padding = '0';
paragraph.style.lineHeight = '1.5';
paragraph.style.width = '100%';
paragraph.style.position = 'relative';
// Process characters in this line
line.split('').forEach(char => {
const span = document.createElement('span');
// Special handling for spaces
if (char === ' ') {
span.innerHTML = ' '; // Use non-breaking space
span.style.width = '0.5em'; // Set explicit width for spaces
} else {
span.textContent = char;
}
span.style.opacity = '0';
span.style.display = 'inline-block';
span.style.position = 'relative';
paragraph.appendChild(span);
});
textContainer.appendChild(paragraph);
});
container.appendChild(textContainer);
return container;
}
// Helper function to animate the typewriter text with completion callback
function startTypewriterAnimation(container, delay, completionCallback) {
const paragraphs = container.querySelectorAll('.typewriter-text');
const allChars = [];
// Collect all characters across all paragraphs
paragraphs.forEach(paragraph => {
const chars = paragraph.querySelectorAll('span');
chars.forEach(char => allChars.push(char));
});
setTimeout(() => {
let index = 0;
const interval = setInterval(() => {
if (index < allChars.length) {
allChars[index].style.opacity = '1';
index++;
} else {
clearInterval(interval);
if (typeof completionCallback === 'function') {
completionCallback();
}
}
}, 70); // Speed of typing
}, delay);
}
// Function to show the pulsing image effect after typing finishes
function showPulsingImageEffect() {
// Create container for the image effect
const effectContainer = document.createElement('div');
effectContainer.className = 'pulsing-image-container';
effectContainer.style.position = 'fixed';
effectContainer.style.top = '0';
effectContainer.style.left = '0';
effectContainer.style.width = '100%';
effectContainer.style.height = '100%';
effectContainer.style.display = 'flex';
effectContainer.style.justifyContent = 'center';
effectContainer.style.alignItems = 'center';
effectContainer.style.zIndex = '1002'; // Above the divided screen
effectContainer.style.pointerEvents = 'none'; // Allow clicks to pass through
effectContainer.style.opacity = '0';
effectContainer.style.transition = 'opacity 1s ease';
// Create the image element
const pulsingImage = document.createElement('img');
pulsingImage.src = 'images/realeffect.png';
pulsingImage.className = 'pulsing-image';
pulsingImage.alt = 'Celebration Effect';
// Set initial styles for the image
pulsingImage.style.maxWidth = '90%';
pulsingImage.style.objectFit = 'contain';
pulsingImage.style.objectPosition = 'top center';
pulsingImage.style.willChange = 'transform, filter';
pulsingImage.style.transformOrigin = 'center center';
pulsingImage.style.transform = 'scale(1) rotate(0deg)';
pulsingImage.style.transition = 'transform 0.1s ease, filter 0.1s ease';
// Add image to container
effectContainer.appendChild(pulsingImage);
document.body.appendChild(effectContainer);
// Wait for image to load before showing and starting animation
pulsingImage.onload = () => {
// Apply proper scaling based on orientation
adjustImageToDevice(pulsingImage);
// Show the container
effectContainer.style.opacity = '1';
// Start pulsing animation
startPulsingAnimation(pulsingImage);
};
// Handle window resize to adjust image scaling
window.addEventListener('resize', () => {
adjustImageToDevice(pulsingImage);
});
}
// Function to adjust image size based on device orientation
function adjustImageToDevice(imageElement) {
const isLandscape = window.innerWidth > window.innerHeight;
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
if (isLandscape) {
// For landscape orientation, make width almost the width of the screen
// and crop from the bottom if needed
imageElement.style.width = '90%';
imageElement.style.height = 'auto';
imageElement.style.maxHeight = '90vh';
} else {
// For portrait orientation, fit to width while maintaining aspect ratio
imageElement.style.width = '90%';
imageElement.style.height = 'auto';
imageElement.style.maxHeight = '70vh';
}
// Always ensure the top portion is visible
imageElement.style.objectPosition = 'top center';
}
// Function to animate the pulsing effect
function startPulsingAnimation(imageElement) {
let scaleDirection = 1;
let rotationDirection = 1;
let vibrancyDirection = 1;
let scale = 1;
let rotation = 0;
let vibrancy = 100;
// Random factor to make the animation less predictable
const randomFactor = () => (Math.random() * 0.5) + 0.75;
// Animation interval for pulsing effect
const pulseInterval = setInterval(() => {
// Scale effect (1.0 to 1.05)
scale += 0.005 * scaleDirection * randomFactor();
if (scale >= 1.05) {
scale = 1.05;
scaleDirection = -1;
} else if (scale <= 1) {
scale = 1;
scaleDirection = 1;
}
// Rotation effect (-2 to 2 degrees)
rotation += 0.2 * rotationDirection * randomFactor();
if (rotation >= 2) {
rotation = 2;
rotationDirection = -1;
} else if (rotation <= -2) {
rotation = -2;
rotationDirection = 1;
}
// Vibrancy effect (100% to 130%)
vibrancy += 2 * vibrancyDirection * randomFactor();
if (vibrancy >= 130) {
vibrancy = 130;
vibrancyDirection = -1;
} else if (vibrancy <= 100) {
vibrancy = 100;
vibrancyDirection = 1;
}
// Apply the calculated effects
imageElement.style.transform = `scale(${scale}) rotate(${rotation}deg)`;
imageElement.style.filter = `saturate(${vibrancy}%) contrast(${vibrancy - 20}%)`;
}, 50); // Update every 50ms for smooth animation
// Optionally, stop the animation after a certain time (e.g., 30 seconds)
setTimeout(() => {
clearInterval(pulseInterval);
}, 30000);
}
// Set up event listeners based on device type
if (isMobileDevice()) {