-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemoji-collage.html
844 lines (768 loc) · 30.7 KB
/
emoji-collage.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Emoji Collage Maker</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/preact/10.19.3/preact.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/preact/10.19.3/hooks.umd.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
<style>
.emoji-grid {
display: block;
font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", "Android Emoji";
line-height: 1em;
letter-spacing: -0.4em;
-webkit-text-size-adjust: none;
}
.color-swatch {
width: 24px;
height: 24px;
border-radius: 4px;
border: 1px solid #ccc;
transition: background-color 0.3s;
margin-left: 8px;
}
.collage-container {
overflow: visible;
position: relative;
margin-top: 1rem;
}
.controls-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.zoom-button {
padding: 4px 8px;
background-color: #e2e8f0;
border: none;
border-radius: 4px;
cursor: pointer;
}
.zoom-button:hover {
background-color: #cbd5e1;
}
#processingCanvas {
display: block;
margin-top: 1rem;
border: 1px solid #ccc;
max-width: 100%;
}
</style>
</head>
<body class="bg-gray-100">
<div id="app"></div>
<script>
const { h, render } = window.preact;
const { useState, useEffect, useRef } = window.preactHooks;
// Helper: Convert hex (e.g. "#ffffff") to an RGB array.
const hexToRgb = (hex) => {
hex = hex.replace(/^#/, '');
if (hex.length === 3) {
hex = hex.split('').map(c => c + c).join('');
}
const num = parseInt(hex, 16);
return [(num >> 16) & 255, (num >> 8) & 255, num & 255];
};
// LAB conversion functions for perceptual matching.
function rgbToXyz(r, g, b) {
r /= 255; g /= 255; b /= 255;
r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
return [x, y, z];
}
function xyzToLab(x, y, z) {
const refX = 0.95047, refY = 1.000, refZ = 1.08883;
x /= refX; y /= refY; z /= refZ;
x = x > 0.008856 ? Math.cbrt(x) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.cbrt(y) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.cbrt(z) : (7.787 * z) + (16 / 116);
const L = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [L, a, b];
}
function rgbToLab(r, g, b) {
return xyzToLab(...rgbToXyz(r, g, b));
}
/*
Extract the representative color for an emoji.
We create a 50×50 canvas with a white background, draw the emoji at 40px,
then average the colors of fully opaque (non-white) pixels.
*/
const extractEmojiColor = (emoji) => {
return new Promise((resolve) => {
const canvas = document.createElement('canvas');
canvas.width = 50;
canvas.height = 50;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
ctx.fillStyle = '#FF00FF'; // Hot pink - very uncommon in emojis
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = '40px "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", "Android Emoji"';
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillText(emoji, canvas.width / 2, canvas.height / 2);
// Slight delay to ensure rendering.
setTimeout(() => {
try {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
let r = 0, g = 0, b = 0, count = 0;
for (let i = 0; i < data.length; i += 4) {
// Only count pixels that are fully opaque and not nearly hot-pink.
if (data[i + 3] > 250 && !(data[i] > 250 && data[i + 1] < 5 && data[i + 2] > 250)) {
r += data[i];
g += data[i + 1];
b += data[i + 2];
count++;
}
}
if (count > 0) {
resolve([Math.round(r / count), Math.round(g / count), Math.round(b / count)]);
} else {
resolve([128, 128, 128]);
}
} catch (error) {
console.error('Error analyzing emoji:', error);
resolve([128, 128, 128]);
}
}, 10);
});
};
/* Debug logging helper */
const debug = {
error: (msg, err) => {
console.error(`[Emoji Collage] ${msg}`, err);
return false;
},
log: (msg, ...args) => console.log(`[Emoji Collage] ${msg}`, ...args)
};
/*
Measure emoji width consistency.
Returns true if the emoji renders at the expected width.
*/
const checkEmojiWidth = (emoji) => {
try {
const canvas = document.createElement('canvas');
if (!canvas) {
return debug.error('Failed to create canvas');
}
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) {
return debug.error('Failed to get canvas context');
}
ctx.font = '40px "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", "Android Emoji"';
const metrics = ctx.measureText(emoji);
const expectedWidth = 54.921875;
const actualWidth = metrics.width;
debug.log(`Emoji ${emoji} width: ${actualWidth}px`);
return Math.abs(actualWidth - expectedWidth) <= (expectedWidth * 0.05);
} catch (err) {
return debug.error(`Error measuring emoji ${emoji}:`, err);
}
};
/*
Optimized Emoji Palette Generation.
We iterate over a set of Unicode ranges and add skin tone variations for modifier-capable emojis.
(The unwanted 🔳 emoji is filtered out.)
*/
const initializeEmojiPalette = (() => {
try {
const ranges = [
[0x1F300, 0x1F5FF],
[0x1F600, 0x1F64F],
[0x1F680, 0x1F6FF],
[0x2600, 0x26FF],
[0x2700, 0x27BF],
[0x1F900, 0x1F9FF],
[0x1FA70, 0x1FAFF],
];
const skinTones = [
'\u{1F3FB}', '\u{1F3FC}', '\u{1F3FD}', '\u{1F3FE}', '\u{1F3FF}'
];
const palette = new Set();
let totalChecked = 0;
let totalAccepted = 0;
for (const [start, end] of ranges) {
for (let cp = start; cp <= end; cp++) {
try {
const base = String.fromCodePoint(cp);
if (base === "🔳") continue;
totalChecked++;
if (/^\p{Emoji}$/u.test(base)) {
if (checkEmojiWidth(base)) {
if (/\p{Emoji_Modifier_Base}/u.test(base)) {
palette.add(base);
totalAccepted++;
for (const tone of skinTones) {
const withTone = base + tone;
if (checkEmojiWidth(withTone)) {
palette.add(withTone);
totalAccepted++;
}
}
} else {
palette.add(base);
totalAccepted++;
}
}
}
} catch (err) {
debug.error(`Error processing codepoint ${cp.toString(16)}:`, err);
}
}
}
debug.log(`Palette generation complete. Checked ${totalChecked} emojis, accepted ${totalAccepted}`);
return Array.from(palette);
} catch (err) {
debug.error('Failed to generate emoji palette:', err);
// Return a minimal fallback palette
return ['⚪', '⚫', '🔴', '🔵', '🟡', '🟢', '🟣', '🟤'];
}
})();
const ColorIndex = {
createIndex(emojiColors, backgroundColor) {
const bgRgb = hexToRgb(backgroundColor);
const blendFactor = 0.8;
const index = {
lab: new Map(),
sorted: []
};
/* Pre-compute blended LAB values */
Object.entries(emojiColors).forEach(([emoji, rawRgb]) => {
const blendedRgb = [
Math.round(rawRgb[0] * blendFactor + bgRgb[0] * (1 - blendFactor)),
Math.round(rawRgb[1] * blendFactor + bgRgb[1] * (1 - blendFactor)),
Math.round(rawRgb[2] * blendFactor + bgRgb[2] * (1 - blendFactor))
];
const labColor = rgbToLab(...blendedRgb);
index.lab.set(emoji, labColor);
index.sorted.push([emoji, labColor]);
});
/* Sort by all LAB components for better matching */
index.sorted.sort(([, lab1], [, lab2]) => {
const [l1, a1, b1] = lab1;
const [l2, a2, b2] = lab2;
return l1 - l2 || a1 - a2 || b1 - b2;
});
return index;
},
findSimilar(index, targetLab, threshold = 5) {
const [l] = targetLab;
/* Binary search for starting position */
let pos = index.sorted.findIndex(([, lab]) => lab[0] >= l);
if (pos < 0) pos = index.sorted.length - 1;
/* Collect candidates within threshold */
const matches = [];
/* Scan in both directions */
for (let i = pos; i >= 0 && matches.length < 50; i--) {
const [emoji, lab] = index.sorted[i];
const diff = Math.sqrt(
Math.pow(lab[0] - targetLab[0], 2) +
Math.pow(lab[1] - targetLab[1], 2) +
Math.pow(lab[2] - targetLab[2], 2)
);
if (diff > threshold * 3) break;
matches.push([emoji, diff]);
}
for (let i = pos + 1; i < index.sorted.length && matches.length < 50; i++) {
const [emoji, lab] = index.sorted[i];
const diff = Math.sqrt(
Math.pow(lab[0] - targetLab[0], 2) +
Math.pow(lab[1] - targetLab[1], 2) +
Math.pow(lab[2] - targetLab[2], 2)
);
if (diff > threshold * 3) break;
matches.push([emoji, diff]);
}
/* Handle no matches */
if (matches.length === 0) {
// Find single closest emoji
const [emoji] = index.sorted.reduce((best, current) => {
const [, lab] = current;
const diff = Math.sqrt(
Math.pow(lab[0] - targetLab[0], 2) +
Math.pow(lab[1] - targetLab[1], 2) +
Math.pow(lab[2] - targetLab[2], 2)
);
return diff < best[1] ? [current[0], diff] : best;
}, [null, Infinity]);
return emoji;
}
/* Return random emoji from best matches */
matches.sort((a, b) => a[1] - b[1]);
const bestDiff = matches[0][1];
const candidates = matches.filter(m => m[1] <= bestDiff * 1.05);
return candidates[Math.floor(Math.random() * candidates.length)][0];
}
};
/*
Cache (or compute) emoji colors.
Each emoji is processed via extractEmojiColor and the result is cached in localStorage.
*/
const getCachedEmojiColors = async (updateProgress, updatePartial) => {
const cached = localStorage.getItem('emojiColors');
if (cached) {
updateProgress(100);
return JSON.parse(cached); // Return raw colors
} else {
const colors = {};
let partial = {};
for (const [index, emoji] of initializeEmojiPalette.entries()) {
const result = await extractEmojiColor(emoji);
colors[emoji] = result;
partial[emoji] = result;
if (updatePartial && index % 10 === 0) {
updatePartial({ ...partial });
}
updateProgress(Math.floor(((index + 1) / initializeEmojiPalette.length) * 100));
}
if (updatePartial) updatePartial(partial);
localStorage.setItem('emojiColors', JSON.stringify(colors));
return colors; // Return raw colors
}
};
/*
Suggest a background color by averaging the pixels along the image’s borders.
*/
const suggestBackgroundColor = (imageData) => {
const data = imageData.data;
const { width, height } = imageData;
let totalR = 0, totalG = 0, totalB = 0, count = 0;
const borderWidth = Math.min(10, Math.floor(width * 0.05), Math.floor(height * 0.05));
for (let y = 0; y < borderWidth; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
totalR += data[idx];
totalG += data[idx + 1];
totalB += data[idx + 2];
count++;
}
}
for (let y = height - borderWidth; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
totalR += data[idx];
totalG += data[idx + 1];
totalB += data[idx + 2];
count++;
}
}
for (let y = borderWidth; y < height - borderWidth; y++) {
for (let x = 0; x < borderWidth; x++) {
const idx = (y * width + x) * 4;
totalR += data[idx];
totalG += data[idx + 1];
totalB += data[idx + 2];
count++;
}
for (let x = width - borderWidth; x < width; x++) {
const idx = (y * width + x) * 4;
totalR += data[idx];
totalG += data[idx + 1];
totalB += data[idx + 2];
count++;
}
}
if (!count) return "#ffffff";
const toHex = c => c.toString(16).padStart(2, '0');
return `#${toHex(Math.round(totalR / count))}${toHex(Math.round(totalG / count))}${toHex(Math.round(totalB / count))}`;
};
/************************* App component *************************/
const App = () => {
const [imageData, setImageData] = useState(null);
const [resolution, setResolution] = useState({ width: 32, height: 32 });
const [emojiColors, setEmojiColors] = useState({});
const [processedPalette, setProcessedPalette] = useState({});
const [collage, setCollage] = useState([]);
const [originalImage, setOriginalImage] = useState(null);
const [paletteProgress, setPaletteProgress] = useState(0);
const [colorIndex, setColorIndex] = useState(null);
const [readyToRender, setReadyToRender] = useState(false); //NOSONAR
const canvasRef = useRef(null);
const [processing, setProcessing] = useState(false);
const [zoomLevel, setZoomLevel] = useState(1);
const [bgColor, setBgColor] = useState('#ffffff');
useEffect(() => {
const fetchEmojiColors = async () => {
const rawColors = await getCachedEmojiColors(setPaletteProgress, setProcessedPalette);
console.log('Got raw colors:', Object.keys(rawColors).length);
const index = ColorIndex.createIndex(rawColors, bgColor);
if (!index || index.sorted.length === 0) {
console.error('Failed to create valid index');
return;
}
console.log('Setting color index with', index.sorted.length, 'entries');
setColorIndex(index);
setReadyToRender(true);
};
fetchEmojiColors();
}, []);
useEffect(() => {
const handleResize = () => {
if (zoomLevel > calculateMaxZoom()) {
setZoomLevel(calculateMaxZoom());
}
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [collage, resolution, zoomLevel]);
// Update when background color changes
useEffect(() => {
if (emojiColors && Object.keys(emojiColors).length > 0) {
console.log('Updating index for new background color:', bgColor);
const index = ColorIndex.createIndex(emojiColors, bgColor);
if (index && index.sorted.length > 0) {
setColorIndex(index);
}
}
}, [bgColor, emojiColors]);
const calculateResolution = (w, h) => {
const minDimension = 32;
const aspectRatio = w / h;
return w < h
? { width: minDimension, height: Math.round(minDimension / aspectRatio) }
: { width: Math.round(minDimension * aspectRatio), height: minDimension };
};
const updateResolution = (newW, newH, isWidth) => {
if (!originalImage || !canvasRef.current) return;
const aspect = originalImage.width / originalImage.height;
let updatedW, updatedH;
if (isWidth) {
updatedW = newW;
updatedH = Math.round(newW / aspect);
} else {
updatedH = newH;
updatedW = Math.round(newH * aspect);
}
setResolution({ width: updatedW, height: updatedH });
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
canvas.width = updatedW;
canvas.height = updatedH;
ctx.drawImage(originalImage, 0, 0, updatedW, updatedH);
setImageData(ctx.getImageData(0, 0, updatedW, updatedH));
setCollage([]);
setReadyToRender(true);
};
const handleImageUpload = (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (evt) => {
const img = new Image();
img.onload = () => {
setOriginalImage(img);
const newRes = calculateResolution(img.width, img.height);
setResolution(newRes);
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
canvas.width = newRes.width;
canvas.height = newRes.height;
ctx.drawImage(img, 0, 0, newRes.width, newRes.height);
const imgData = ctx.getImageData(0, 0, newRes.width, newRes.height);
setImageData(imgData);
const suggested = suggestBackgroundColor(imgData);
setBgColor(suggested);
setCollage([]);
setReadyToRender(true);
};
img.onerror = (err) => console.error('Image load error:', err);
img.src = evt.target.result;
};
reader.onerror = (err) => console.error('File read error:', err);
reader.readAsDataURL(file);
};
/*
Generate the collage.
For each image pixel, we:
1. Convert the pixel’s color to LAB.
2. Find the closest emoji in the Color Index based on LAB distance.
*/
const generateCollage = () => {
if (!imageData || !colorIndex) {
console.error('Missing data:', { hasImageData: !!imageData, colorIndex });
return;
}
console.log('Starting generation with colorIndex:', colorIndex);
setProcessing(true);
const data = imageData.data;
const newCollage = [];
for (let y = 0; y < resolution.height; y++) {
const row = [];
for (let x = 0; x < resolution.width; x++) {
const i = (y * resolution.width + x) * 4;
const labColor = rgbToLab(data[i], data[i + 1], data[i + 2]);
// Add debug log for first pixel
if (x === 0 && y === 0) {
console.log('First pixel:', {
rgb: [data[i], data[i + 1], data[i + 2]],
lab: labColor,
colorIndex: colorIndex
});
}
const emoji = ColorIndex.findSimilar(colorIndex, labColor);
row.push(emoji);
}
newCollage.push(row);
}
setCollage(newCollage);
setProcessing(false);
};
const downloadPNG = () => {
if (!collage.length) return;
const tempCanvas = document.createElement('canvas');
const scale = 30;
tempCanvas.width = resolution.width * scale;
tempCanvas.height = resolution.height * scale;
const ctx = tempCanvas.getContext('2d', { willReadFrequently: true });
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
ctx.font = `${scale}px "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", "Android Emoji"`;
ctx.textBaseline = 'top';
for (let y = 0; y < resolution.height; y++) {
for (let x = 0; x < resolution.width; x++) {
ctx.fillText(collage[y][x], x * scale, y * scale);
}
}
tempCanvas.toBlob((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'emoji_collage.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}, 'image/png');
};
const downloadSVG = () => {
if (!collage.length) return;
const emojiSize = 20;
const svgW = resolution.width * emojiSize;
const svgH = resolution.height * emojiSize;
let svgContent = `<svg xmlns="http://www.w3.org/2000/svg" width="${svgW}" height="${svgH}">`;
svgContent += `<rect width="100%" height="100%" fill="${bgColor}"/>`;
svgContent += `<text font-size="${emojiSize}" font-family="Apple Color Emoji, Segoe UI Emoji, Noto Color Emoji, Android Emoji">`;
for (let y = 0; y < resolution.height; y++) {
for (let x = 0; x < resolution.width; x++) {
svgContent += `<tspan x="${x * emojiSize}" y="${(y + 1) * emojiSize}">${collage[y][x]}</tspan>`;
}
}
svgContent += '</text></svg>';
const blob = new Blob([svgContent], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'emoji_collage.svg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
const openFullPage = () => {
if (!collage.length) return;
const baseFontSize = Math.max(6, Math.min(32, 800 / resolution.width));
const effectiveFontSize = baseFontSize * zoomLevel;
const htmlContent = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Emoji Collage</title>
<style>
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: ${bgColor};
}
.emoji-grid {
display: block;
font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", "Android Emoji";
line-height: 1em;
letter-spacing: -0.4em;
}
</style>
</head>
<body>
<div class="emoji-grid">
${collage.map(row => `<div class="emoji-row">${row.join('')}</div>`).join('\n')}
</div>
</body>
</html>
`;
const newWindow = window.open('', '_blank');
if (newWindow) {
newWindow.document.open();
newWindow.document.write(htmlContent);
newWindow.document.close();
} else {
alert('Pop-up blocked. Please allow pop-ups for this website.');
}
};
const calculateMaxZoom = () => {
if (!collage.length || !resolution) return 3;
const viewportWidth = window.innerWidth * 0.9; // 90% of viewport width
const viewportHeight = window.innerHeight * 0.7; // 70% of viewport height to account for controls
const baseFontSize = Math.max(8, Math.min(32, 800 / resolution.width));
const maxWidthZoom = viewportWidth / (resolution.width * baseFontSize);
const maxHeightZoom = viewportHeight / (resolution.height * baseFontSize);
return Math.max(1, Math.min(maxWidthZoom, maxHeightZoom, 3));
};
const increaseZoom = () => {
const maxZoom = calculateMaxZoom();
setZoomLevel(prev => Math.min(prev + 0.1, maxZoom));
};
const decreaseZoom = () => setZoomLevel(prev => Math.max(prev - 0.1, 0.2));
const resetZoom = () => {
const maxZoom = calculateMaxZoom();
setZoomLevel(Math.min(1, maxZoom));
};
let collagePreview = null;
if (collage.length > 0) {
const baseFontSize = Math.max(8, Math.min(32, 800 / resolution.width));
const effectiveFontSize = baseFontSize * zoomLevel;
collagePreview = h('div', {
className: 'collage-container',
style: {
width: (resolution.width * effectiveFontSize) + 'px',
height: (resolution.height * effectiveFontSize) + 'px',
backgroundColor: bgColor
}
}, [
h('div', {
className: 'emoji-grid',
style: { fontSize: effectiveFontSize + 'px' }
},
collage.map((row, rowIndex) =>
h('div', {
key: rowIndex,
className: 'emoji-row'
}, row.join(''))
)
)
]);
}
let palettePreview = null;
if (paletteProgress < 100) {
const keys = Object.keys(processedPalette);
const sample = keys.length <= 50 ? keys : keys.slice(-50);
palettePreview = h('div', { className: 'mt-4' }, [
h('h2', { className: 'text-md font-medium mb-2' }, 'Palette Processing Preview:'),
h('div', { className: 'grid grid-cols-10 gap-1' },
sample.map(emoji => {
const color = processedPalette[emoji];
return h('div', {
key: emoji,
style: {
backgroundColor: color ? `rgb(${color[0]}, ${color[1]}, ${color[2]})` : '#fff',
border: '1px solid #ccc',
width: '2em',
height: '2em',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}
}, emoji);
})
)
]);
}
const lowerSection = h('div', { style: { backgroundColor: bgColor, width: '100%' } }, [
h('div', { className: 'p-6 max-w-6xl mx-auto' }, [
h('div', { className: 'bg-white p-4 rounded shadow mt-4 flex flex-col gap-4' }, [
originalImage && h('button', {
onClick: generateCollage,
className: 'px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50',
disabled: processing || paletteProgress < 100
}, paletteProgress < 100 ? 'Building Emoji Palette...' : (processing ? 'Generating...' : 'Generate Collage')),
collage.length > 0 && h('div', { className: 'controls-row' }, [
h('button', { onClick: downloadPNG, className: 'px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600' }, 'Download as PNG'),
h('button', { onClick: downloadSVG, className: 'px-4 py-2 bg-indigo-500 text-white rounded hover:bg-indigo-600' }, 'Download as SVG'),
h('button', { onClick: openFullPage, className: 'px-4 py-2 bg-yellow-500 text-white rounded hover:bg-yellow-600' }, 'Open as Full Page'),
h('button', { onClick: decreaseZoom, className: 'zoom-button', title: 'Zoom Out' }, '-'),
h('button', { onClick: resetZoom, className: 'zoom-button', title: 'Reset' }, 'Reset'),
h('button', { onClick: increaseZoom, className: 'zoom-button', title: 'Zoom In' }, '+')
])
]),
collagePreview,
h('div', { className: 'mt-6 text-center text-sm text-gray-500' }, '© 2025 Emoji Collage Maker')
])
]);
return h('div', { className: 'p-6 max-w-6xl mx-auto' }, [
h('h1', { className: 'text-4xl font-bold mb-6 text-center' }, 'Emoji Collage Maker'),
h('div', { className: 'bg-white p-4 rounded shadow' }, [
h('div', { className: 'flex flex-wrap gap-4' }, [
h('div', { className: 'flex-1 min-w-[250px]' }, [
h('div', { className: 'space-y-2 mb-4' }, [
h('label', { className: 'block text-sm font-medium' }, 'Upload Image:'),
h('input', {
type: 'file',
accept: 'image/*',
onChange: handleImageUpload,
className: 'block w-full text-sm text-gray-500'
})
]),
originalImage && h('div', { className: 'space-y-2 mb-4' }, [
h('label', { className: 'block text-sm font-medium' }, 'Resolution:'),
h('div', { className: 'flex gap-2 items-center' }, [
h('input', {
type: 'number',
value: resolution.width,
onChange: (e) => updateResolution(+e.target.value, resolution.height, true),
className: 'w-20 px-2 py-1 border rounded'
}),
h('span', null, '×'),
h('input', {
type: 'number',
value: resolution.height,
onChange: (e) => updateResolution(resolution.width, +e.target.value, false),
className: 'w-20 px-2 py-1 border rounded'
})
])
]),
originalImage && h('div', { className: 'space-y-2 mb-4' }, [
h('label', { className: 'block text-sm font-medium' }, 'Background Color:'),
h('input', {
type: 'color',
value: bgColor,
onChange: (e) => setBgColor(e.target.value),
className: 'w-12 h-12 p-0 border rounded'
})
]),
h('canvas', { ref: canvasRef, id: 'processingCanvas' }),
h('div', { className: 'text-sm text-gray-600 mb-4' },
paletteProgress < 100
? `Building emoji palette: ${paletteProgress}% complete (cached for future collage generations)...`
: 'Emoji palette ready!'
),
palettePreview
]),
originalImage && h('div', { className: 'flex-shrink-0' }, [
h('h2', { className: 'text-lg font-medium mb-2' }, 'Original Image:'),
h('img', {
src: originalImage.src,
className: 'border rounded',
style: { maxHeight: '500px', maxWidth: '100%' }
})
])
])
]),
lowerSection
]);
};
render(h(App), document.getElementById('app'));
</script>
</body>
</html>