Repository navigation
Expand file tree
/
Copy path11.html
More file actions
1362 lines (1227 loc) · 45.6 KB
/
Copy path11.html
File metadata and controls
1362 lines (1227 loc) · 45.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Advanced ASCII Art Studio - Enhanced with Advanced Tools</title>
<script src="https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.js"></script>
<script src="https://unpkg.com/@ffmpeg/ffmpeg@0.11.0/dist/ffmpeg.min.js"></script>
<style>
:root {
--bg-color: #1a1a1d;
--surface-color: #2c2f33;
--primary-color: #66fcf1;
--secondary-color: #45a29e;
--text-color: #c5c6c7;
--text-muted-color: #99aab5;
--dark-color: #0b0c10;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
margin: 0;
padding: 24px;
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
box-sizing: border-box;
}
h1 {
color: var(--primary-color);
border-bottom: 2px solid var(--secondary-color);
padding-bottom: 10px;
margin-top: 0;
}
.main-container {
display: flex;
width: 100%;
max-width: 1800px;
gap: 24px;
flex-grow: 1;
}
.controls-panel {
background-color: var(--surface-color);
padding: 20px;
border-radius: 8px;
width: 420px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
height: fit-content;
display: flex;
flex-direction: column;
gap: 15px;
}
.preview-panel {
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 16px;
}
.canvas-container {
flex-grow: 1;
background-color: var(--dark-color);
border-radius: 8px;
padding: 16px;
display: flex;
justify-content: center;
align-items: center;
overflow: auto;
min-height: 400px;
color: var(--primary-color);
font-family: monospace;
white-space: pre;
font-size: 10px;
line-height: 1.1em;
}
#ascii-preview {
max-width: 100%;
max-height: 100%;
overflow: auto;
}
#preview-canvas {
background-color: black;
max-width: 100%;
max-height: 100%;
object-fit: contain;
display: none; /* Hide canvas, we use ASCII text preview */
}
.export-panel {
background-color: var(--surface-color);
padding: 16px;
border-radius: 8px;
display: flex;
gap: 12px;
justify-content: center;
}
fieldset {
border: 1px solid var(--secondary-color);
border-radius: 5px;
padding: 12px;
}
legend {
color: var(--primary-color);
font-weight: bold;
padding: 0 8px;
}
.control-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 6px;
font-size: 0.9em;
}
input[type="file"], select, input[type="text"], button, input[type="color"], input[type="range"] {
width: 100%;
padding: 10px;
border-radius: 4px;
border: 1px solid #4f545c;
background-color: #40444b;
color: var(--text-color);
box-sizing: border-box;
}
input[type="color"] {
padding: 5px;
min-height: 40px;
}
input[type="range"] {
padding: 0;
}
button {
background-color: var(--primary-color);
color: var(--dark-color);
font-weight: bold;
cursor: pointer;
border: none;
transition: background-color 0.3s, transform 0.1s;
}
button:hover:not(:disabled) {
background-color: var(--secondary-color);
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:disabled {
background-color: #4f545c;
color: var(--text-muted-color);
cursor: not-allowed;
}
.range-value {
font-size: 0.8em;
color: var(--text-muted-color);
text-align: right;
}
.info {
font-size: 0.8em;
color: var(--text-muted-color);
margin-top: 5px;
line-height: 1.4;
}
.status-bar {
width: 100%;
text-align: center;
margin-top: 16px;
color: var(--text-muted-color);
min-height: 20px;
}
progress {
width: 100%;
}
/* Neon glow styles with variable intensity */
.wild-neon-char {
display: inline-block;
vertical-align: top;
user-select: none;
}
</style>
</head>
<body>
<h1>Advanced ASCII Art Studio</h1>
<div class="main-container">
<div class="controls-panel">
<fieldset>
<legend>Source</legend>
<div class="control-group">
<label for="image-loader">Image / Video / Tween Start</label>
<input type="file" id="image-loader" accept="image/*,video/*" />
</div>
<div class="control-group">
<label for="image-loader-end">Tween End Image (Optional)</label>
<input type="file" id="image-loader-end" accept="image/*" />
</div>
<button id="webcam-btn">Use Webcam</button>
</fieldset>
<fieldset>
<legend>Core Settings</legend>
<div class="control-group">
<label for="method">Generation Method</label>
<select id="method">
<option value="tonal" selected>Tonal (Luminance)</option>
<option value="structural">Structural (Edge-Detection)</option>
</select>
</div>
<div class="control-group">
<label for="output-width">Output Width (characters)</label>
<input type="range" id="output-width" min="40" max="400" value="150" />
<div class="range-value" id="output-width-value">150</div>
</div>
</fieldset>
<fieldset id="tonal-settings">
<legend>Tonal Settings</legend>
<div class="control-group">
<label for="contrast">Contrast Boost</label>
<input type="range" id="contrast" min="1.0" max="5.0" value="1.5" step="0.1" />
<div class="range-value" id="contrast-value">1.5</div>
</div>
<div class="control-group">
<label><input type="checkbox" id="dithering" checked /> Floyd-Steinberg Dithering</label>
</div>
<div class="control-group">
<label for="char-ramp">Character Set</label>
<select id="char-ramp">
<option value="standard">Standard (70)</option>
<option value="simple" selected>Simple (10)</option>
<option value="blocks">Blocks</option>
<option value="custom">Custom</option>
</select>
<input type="text" id="custom-ramp" value="@%#*+=-:. " style="display:none;" />
</div>
</fieldset>
<fieldset id="structural-settings" disabled>
<legend>Structural Settings</legend>
<div class="control-group">
<label for="edge-threshold">Edge Threshold</label>
<input type="range" id="edge-threshold" min="10" max="200" value="50" step="1" />
<div class="range-value" id="edge-threshold-value">50</div>
</div>
<div class="control-group">
<label for="blur-radius">Noise Reduction (Blur)</label>
<input type="range" id="blur-radius" min="0" max="5" value="1" step="1" />
<div class="range-value" id="blur-radius-value">1</div>
</div>
</fieldset>
<fieldset>
<legend>Style & Font</legend>
<div class="control-group">
<label for="color-mode">Color Mode</label>
<select id="color-mode">
<option value="mono">Monochrome</option>
<option value="grayscale">Grayscale</option>
<option value="duotone">Duotone</option>
<option value="sepia">Sepia</option>
<option value="inverted">Inverted</option>
<option value="tritone">Tri-tone</option>
<option value="quadtone">Quad-tone</option>
<option value="color" selected>Full Color</option>
</select>
</div>
<div class="control-group" id="mono-color-group">
<label for="mono-color">Monochrome Color</label>
<input type="color" id="mono-color" value="#66fcf1" />
</div>
<div class="control-group">
<label for="bg-color">Background Color</label>
<input type="color" id="bg-color" value="#0000" />
</div>
<div class="control-group">
<label><input type="checkbox" id="invert-colors" /> Invert Character Ramp</label>
</div>
<div class="control-group">
<label for="font-loader">Custom Font (.ttf, .otf)</label>
<input type="file" id="font-loader" accept=".ttf,.otf" />
</div>
<div class="control-group">
<label><input type="checkbox" id="wild-neon-toggle" /> Enable Wild Neon Colors & Random Font Size</label>
</div>
<div class="control-group">
<label for="neon-palette">Neon Color Palette</label>
<select id="neon-palette">
<option value="original" selected>Original Neon</option>
<option value="white-yellow">White instead of Yellow</option>
</select>
</div>
<div class="control-group">
<label for="font-size-delta">Font Size Variation Delta (chars)</label>
<input type="range" id="font-size-delta" min="1" max="20" value="1" />
<div class="range-value" id="font-size-delta-value">1</div>
</div>
<div class="control-group">
<label for="neon-glow-intensity">Neon Glow Intensity: <span id="neon-glow-value">5</span></label>
<input type="range" id="neon-glow-intensity" min="0" max="10" value="5" />
</div>
</fieldset>
<fieldset>
<legend>Animation</legend>
<div class="control-group">
<label for="fps">Frames Per Second (FPS)</label>
<input type="range" id="fps" min="1" max="30" value="15" />
<div class="range-value" id="fps-value">15</div>
</div>
<div class="control-group" id="tween-frames-group" style="display: none;">
<label for="tween-frames">Tween Frames</label>
<input type="range" id="tween-frames" min="10" max="120" value="30" />
<div class="range-value" id="tween-frames-value">30</div>
</div>
</fieldset>
<button id="generate-btn">Generate</button>
</div>
<div class="preview-panel">
<div class="canvas-container" tabindex="0" aria-label="ASCII art preview">
<pre id="ascii-preview" aria-live="polite" aria-atomic="true">No ASCII art generated yet.</pre>
<canvas id="preview-canvas"></canvas>
</div>
<div class="export-panel">
<button id="export-png-btn" disabled>Export as PNG</button>
<button id="export-gif-btn" disabled>Export as GIF</button>
<button id="export-mp4-btn" disabled>Export as MP4</button>
</div>
<div class="status-bar">
<div id="status">Select an image, video, or use your webcam to start.</div>
<progress id="progress-bar" style="display: none;"></progress>
<div id="ffmpeg-note" class="info" style="display: none;">
Note: MP4 export is CPU-intensive. For faster exports, host this file on a server with COOP/COEP headers enabled.
</div>
</div>
</div>
</div>
<script>
// --- DOM Elements ---
const imageLoader = document.getElementById('image-loader');
const imageLoaderEnd = document.getElementById('image-loader-end');
const generateBtn = document.getElementById('generate-btn');
const webcamBtn = document.getElementById('webcam-btn');
const previewCanvas = document.getElementById('preview-canvas');
const ctx = previewCanvas.getContext('2d');
const asciiPreview = document.getElementById('ascii-preview');
const statusEl = document.getElementById('status');
const progressBar = document.getElementById('progress-bar');
const ffmpegNote = document.getElementById('ffmpeg-note');
const exportPngBtn = document.getElementById('export-png-btn');
const exportGifBtn = document.getElementById('export-gif-btn');
const exportMp4Btn = document.getElementById('export-mp4-btn');
const controls = {
outputWidth: document.getElementById('output-width'),
outputWidthValue: document.getElementById('output-width-value'),
method: document.getElementById('method'),
contrast: document.getElementById('contrast'),
contrastValue: document.getElementById('contrast-value'),
dithering: document.getElementById('dithering'),
charRamp: document.getElementById('char-ramp'),
customRamp: document.getElementById('custom-ramp'),
edgeThreshold: document.getElementById('edge-threshold'),
edgeThresholdValue: document.getElementById('edge-threshold-value'),
blurRadius: document.getElementById('blur-radius'),
blurRadiusValue: document.getElementById('blur-radius-value'),
colorMode: document.getElementById('color-mode'),
bgColor: document.getElementById('bg-color'),
invertColors: document.getElementById('invert-colors'),
fontLoader: document.getElementById('font-loader'),
fps: document.getElementById('fps'),
fpsValue: document.getElementById('fps-value'),
tweenFrames: document.getElementById('tween-frames'),
tweenFramesValue: document.getElementById('tween-frames-value'),
tweenFramesGroup: document.getElementById('tween-frames-group'),
wildNeonToggle: document.getElementById('wild-neon-toggle'),
neonGlowIntensity: document.getElementById('neon-glow-intensity'),
neonGlowValue: document.getElementById('neon-glow-value'),
neonPalette: document.getElementById('neon-palette'),
fontSizeDelta: document.getElementById('font-size-delta'),
fontSizeDeltaValue: document.getElementById('font-size-delta-value'),
monoColor: document.getElementById('mono-color'),
monoColorGroup: document.getElementById('mono-color-group'),
};
// --- State ---
let animationFrameId = null;
let mediaSource = null;
let mediaType = 'none';
let sourceFrames = [];
let customFontName = 'monospace';
let gifWorkerBlob = null;
let webcamStream = null;
// --- FFmpeg & GIF.js Setup ---
const { createFFmpeg, fetchFile } = FFmpeg;
const ffmpeg = createFFmpeg({
log: true,
corePath: 'https://unpkg.com/@ffmpeg/core-st@0.11.1/dist/ffmpeg-core.js',
});
// Pre-fetch the GIF worker script to create a blob URL, avoiding cross-origin issues
fetch('https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.worker.js')
.then(response => response.blob())
.then(blob => gifWorkerBlob = URL.createObjectURL(blob))
.catch(err => console.error("Failed to load GIF worker:", err));
// --- UI Event Listeners ---
// Update range value displays
[
['outputWidth', 'outputWidthValue'],
['contrast', 'contrastValue'],
['edgeThreshold', 'edgeThresholdValue'],
['blurRadius', 'blurRadiusValue'],
['fps', 'fpsValue'],
['tweenFrames', 'tweenFramesValue'],
['fontSizeDelta', 'fontSizeDeltaValue'],
].forEach(([rangeId, valueId]) => {
const range = controls[rangeId];
const value = controls[valueId];
if (range && value) {
range.addEventListener('input', () => {
value.textContent = range.value;
if (rangeId === 'fontSizeDelta' && mediaSource) {
generateAndRenderCurrent();
}
});
value.textContent = range.value;
}
});
// Neon glow intensity slider update
controls.neonGlowIntensity.addEventListener('input', () => {
controls.neonGlowValue.textContent = controls.neonGlowIntensity.value;
if (controls.wildNeonToggle.checked && mediaSource) {
generateAndRenderCurrent();
}
});
// Show/hide custom ramp input
controls.charRamp.addEventListener('change', () => {
controls.customRamp.style.display = controls.charRamp.value === 'custom' ? 'block' : 'none';
});
// Enable/disable tonal vs structural settings
controls.method.addEventListener('change', () => {
const isTonal = controls.method.value === 'tonal';
document.getElementById('tonal-settings').disabled = !isTonal;
document.getElementById('structural-settings').disabled = isTonal;
});
// Update media type on file input changes
imageLoader.addEventListener('change', updateSourceState);
imageLoaderEnd.addEventListener('change', updateSourceState);
// Wild neon toggle change: re-render preview
controls.wildNeonToggle.addEventListener('change', () => {
if (mediaSource) {
generateAndRenderCurrent();
}
});
// Neon palette change: re-render preview
controls.neonPalette.addEventListener('change', () => {
if (mediaSource) {
generateAndRenderCurrent();
}
});
// Color mode change: show/hide monochrome color picker and re-render
controls.colorMode.addEventListener('change', () => {
controls.monoColorGroup.style.display = controls.colorMode.value === 'mono' ? 'block' : 'none';
if (mediaSource) {
generateAndRenderCurrent();
}
});
// Monochrome color picker change: re-render
controls.monoColor.addEventListener('input', () => {
if (mediaSource && controls.colorMode.value === 'mono') {
generateAndRenderCurrent();
}
});
// Load custom font
controls.fontLoader.addEventListener('change', async (e) => {
if (e.target.files.length === 0) return;
const fontFile = e.target.files[0];
try {
customFontName = 'custom-font-' + Date.now();
const font = new FontFace(customFontName, await fontFile.arrayBuffer());
await font.load();
document.fonts.add(font);
setStatus(`Loaded font: ${fontFile.name}`);
if (mediaSource) generateAndRenderCurrent();
} catch (err) {
setStatus(`Error loading font: ${err.message}`);
customFontName = 'monospace'; // Fallback
}
});
// --- Functions ---
function updateSourceState() {
const startFile = imageLoader.files.length > 0 ? imageLoader.files[0] : null;
const endFile = imageLoaderEnd.files.length > 0 ? imageLoaderEnd.files[0] : null;
if (startFile && endFile) {
mediaType = 'tween';
controls.tweenFramesGroup.style.display = 'block';
} else if (startFile) {
if (startFile.type.startsWith('video/')) {
mediaType = 'video';
} else if (startFile.type.startsWith('image/')) {
mediaType = 'image';
} else {
mediaType = 'none';
}
controls.tweenFramesGroup.style.display = 'none';
imageLoaderEnd.value = ''; // Clear end file if start file is changed
} else {
mediaType = 'none';
controls.tweenFramesGroup.style.display = 'none';
}
updateExportButtons();
}
function setUIState(isProcessing) {
generateBtn.disabled = isProcessing;
webcamBtn.disabled = isProcessing;
exportPngBtn.disabled = isProcessing;
exportGifBtn.disabled = isProcessing;
exportMp4Btn.disabled = isProcessing;
progressBar.style.display = isProcessing ? 'block' : 'none';
if (!isProcessing) progressBar.removeAttribute('value');
}
function setStatus(message) {
statusEl.textContent = message;
}
function triggerDownload(href, filename) {
const a = document.createElement('a');
a.href = href;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
// Load image helper
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => resolve(img);
img.onerror = () => reject(new Error('Failed to load image'));
img.src = src;
});
}
// Load video helper
function loadVideo(src) {
return new Promise((resolve, reject) => {
const video = document.createElement('video');
video.onloadedmetadata = () => resolve(video);
video.onerror = () => reject(new Error('Failed to load video'));
video.src = src;
video.load();
});
}
// --- ASCII Generation Logic ---
// Floyd-Steinberg dithering
function floydSteinbergDithering(data, width, height) {
const d = Array.from(data);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = y * width + x;
const oldPixel = d[i];
const newPixel = oldPixel < 128 ? 0 : 255;
d[i] = newPixel;
const quantError = oldPixel - newPixel;
if (x + 1 < width) d[i + 1] += quantError * 7 / 16;
if (x - 1 >= 0 && y + 1 < height) d[i + width - 1] += quantError * 3 / 16;
if (y + 1 < height) d[i + width] += quantError * 5 / 16;
if (x + 1 < width && y + 1 < height) d[i + width + 1] += quantError * 1 / 16;
}
}
return Uint8ClampedArray.from(d);
}
// Canny edge detector (simplified)
// For brevity, this example uses a simple edge detection by Sobel filter
function cannyEdgeDetector(imageData, options) {
const { width, height, data } = imageData;
const gray = new Uint8ClampedArray(width * height);
for (let i = 0; i < data.length; i += 4) {
gray[i / 4] = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
}
// Sobel kernels
const sobelX = [-1,0,1,-2,0,2,-1,0,1];
const sobelY = [-1,-2,-1,0,0,0,1,2,1];
const edgeData = new Uint8ClampedArray(width * height);
for (let y = 1; y < height -1; y++) {
for (let x = 1; x < width -1; x++) {
let gx = 0, gy = 0;
for (let ky = -1; ky <=1; ky++) {
for (let kx = -1; kx <=1; kx++) {
const val = gray[(y+ky)*width + (x+kx)];
const idx = (ky+1)*3 + (kx+1);
gx += val * sobelX[idx];
gy += val * sobelY[idx];
}
}
const mag = Math.sqrt(gx*gx + gy*gy);
edgeData[y*width + x] = mag > options.edgeThreshold ? 255 : 0;
}
}
return edgeData;
}
// Generate ASCII art string from image data
function generateAscii(img, options) {
const aspectRatio = img.height / img.width;
const width = options.width;
const height = Math.round(aspectRatio * width * 0.55);
// Draw resized image to temp canvas
const tempCanvas = document.createElement('canvas');
tempCanvas.width = width;
tempCanvas.height = height;
const tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(img, 0, 0, width, height);
const imageData = tempCtx.getImageData(0, 0, width, height);
const data = imageData.data;
// Convert to grayscale luminance
let grayData = new Uint8ClampedArray(width * height);
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
grayData[i / 4] = 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Apply contrast boost
if (options.contrast !== 1.0) {
for (let i = 0; i < grayData.length; i++) {
let val = grayData[i] / 255;
val = ((val - 0.5) * options.contrast + 0.5);
val = Math.min(1, Math.max(0, val));
grayData[i] = val * 255;
}
}
// Apply dithering if enabled
if (options.dithering) {
grayData = floydSteinbergDithering(grayData, width, height);
}
// Choose character ramp
const ramps = {
standard: `$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}?-_+~<>i!lI;:,"^'\`. `,
simple: `.:-=+*#%@`,
blocks: ` ░▒▓█`
};
let ramp = ramps[options.charRamp] || options.charRamp;
if (options.charRamp === 'custom') {
ramp = options.customRamp || '@%#*+=-:. ';
}
if (options.invertColors) {
ramp = ramp.split('').reverse().join('');
}
// Generate ASCII string
let ascii = '';
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = y * width + x;
const lum = grayData[i];
const charIndex = Math.floor((lum / 255) * (ramp.length - 1));
ascii += ramp[charIndex];
}
ascii += '\n';
}
return ascii;
}
// Neon colors palettes
const neonPalettes = {
original: [
'#0ff', '#ff00ff', '#39ff14', '#ff1493', '#00ffff', '#7fff00', '#ff4500', '#ff69b4'
],
'white-yellow': [
'#0ff', '#ff00ff', '#39ff14', '#ff1493', '#00ffff', '#ffffff', '#ff4500', '#ff69b4'
]
};
// Additional color palettes for semi-color modes
const duotoneColors = ['#66fcf1', '#ff69b4']; // cyan and pink
const sepiaColors = ['#704214', '#c0a080']; // dark brown and light brown
const tritoneColors = ['#66fcf1', '#ff69b4', '#7fff00']; // cyan, pink, lime
const quadtoneColors = ['#66fcf1', '#ff69b4', '#7fff00', '#ff4500']; // cyan, pink, lime, orange
// Helper: map luminance to color in a palette (linear)
function mapLuminanceToPalette(lum, palette) {
const n = palette.length;
const idx = Math.min(n - 1, Math.floor(lum * n));
return palette[idx];
}
// Helper: get monochrome color from picker
function getMonochromeColor() {
return controls.monoColor.value || '#66fcf1';
}
// Helper: invert RGB color string
function invertColor(rgb) {
// rgb format: "rgb(r,g,b)"
const m = rgb.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
if (!m) return rgb;
const r = 255 - parseInt(m[1]);
const g = 255 - parseInt(m[2]);
const b = 255 - parseInt(m[3]);
return `rgb(${r},${g},${b})`;
}
// Helper: convert rgb string to [r,g,b]
function rgbStringToArray(rgb) {
const m = rgb.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
if (!m) return [0,0,0];
return [parseInt(m[1]), parseInt(m[2]), parseInt(m[3])];
}
// Helper: convert rgb array to string
function rgbArrayToString(arr) {
return `rgb(${arr[0]},${arr[1]},${arr[2]})`;
}
// Helper: convert rgb to grayscale luminance 0-1
function rgbToLuminance(r,g,b) {
return (0.2126*r + 0.7152*g + 0.0722*b)/255;
}
// Helper: apply sepia tone to rgb array
function applySepia(r,g,b) {
const tr = 0.393*r + 0.769*g + 0.189*b;
const tg = 0.349*r + 0.686*g + 0.168*b;
const tb = 0.272*r + 0.534*g + 0.131*b;
return [
Math.min(255, tr),
Math.min(255, tg),
Math.min(255, tb)
];
}
// Helper: apply color mode to rgb color based on luminance and mode
function applyColorMode(r,g,b, lum, mode) {
switch(mode) {
case 'mono':
return hexToRgb(getMonochromeColor());
case 'grayscale':
const gray = Math.round(lum * 255);
return [gray, gray, gray];
case 'duotone':
return hexToRgb( mapLuminanceToPalette(lum, duotoneColors) );
case 'sepia':
return applySepia(r,g,b);
case 'inverted':
return [255 - r, 255 - g, 255 - b];
case 'tritone':
return hexToRgb( mapLuminanceToPalette(lum, tritoneColors) );
case 'quadtone':
return hexToRgb( mapLuminanceToPalette(lum, quadtoneColors) );
case 'color':
default:
return [r,g,b];
}
}
// Helper: convert hex color to rgb array
function hexToRgb(hex) {
// Remove #
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];
}
// Helper to create neon glow text-shadow string based on intensity and color
function createNeonTextShadow(color, intensity) {
if (intensity <= 0) return 'none';
const baseBlur = intensity * 1.5;
const shadows = [
`0 0 ${baseBlur}px ${color}`,
`0 0 ${baseBlur * 2}px ${color}`,
`0 0 ${baseBlur * 4}px ${color}`,
`0 0 ${baseBlur * 8}px ${color}`
];
return shadows.join(', ');
}
// Helper: get neon palette array based on selection
function getNeonPalette() {
return neonPalettes[controls.neonPalette.value] || neonPalettes.original;
}
// Helper: get random neon color from selected palette
function getRandomNeonColor() {
const palette = getNeonPalette();
return palette[Math.floor(Math.random() * palette.length)];
}
// Render ASCII string to preview panel with optional color and wild neon mode
function renderAsciiPreview(asciiStr, img, options) {
const wildNeonEnabled = controls.wildNeonToggle.checked;
const neonGlowIntensity = parseInt(controls.neonGlowIntensity.value);
const fontSizeDelta = parseInt(controls.fontSizeDelta.value);
const colorMode = controls.colorMode.value;
if (wildNeonEnabled) {
asciiPreview.style.display = 'block';
previewCanvas.style.display = 'none';
asciiPreview.innerHTML = '';
const lines = asciiStr.split('\n');
for (const line of lines) {
const lineSpan = document.createElement('div');
let currentFontSize = getRandomInt(8, 16);
let charCountSinceChange = 0;
for (const ch of line) {
const span = document.createElement('span');
span.textContent = ch === ' ' ? '\u00A0' : ch;
// Change font size only every fontSizeDelta chars
if (charCountSinceChange >= fontSizeDelta) {
currentFontSize = getRandomInt(8, 16);
charCountSinceChange = 0;
}
charCountSinceChange++;
span.style.fontSize = currentFontSize + 'px';
// Neon color from selected palette
const color = getRandomNeonColor();
span.style.color = color;
span.className = 'wild-neon-char';
span.style.textShadow = createNeonTextShadow(color, neonGlowIntensity);
lineSpan.appendChild(span);
}
asciiPreview.appendChild(lineSpan);
}
} else if (colorMode === 'color' && img) {
// Normal colored ASCII using canvas
renderAsciiPreviewCanvas(asciiStr, img, options);
} else {
// Monochrome or semi-color modes on canvas
renderAsciiPreviewCanvas(asciiStr, img, options);
}
}
// Render ASCII string to canvas with color modes (including wild neon)
async function renderAsciiPreviewCanvas(asciiStr, img, options) {
const neonGlowIntensity = parseInt(controls.neonGlowIntensity.value);
const fontSizeDelta = parseInt(controls.fontSizeDelta.value);
const wildNeonEnabled = controls.wildNeonToggle.checked;
const colorMode = controls.colorMode.value;
const lines = asciiStr.split('\n');
const width = lines[0].length;
const height = lines.length;
// Clear and set canvas size
previewCanvas.width = width * 10 * 0.6; // max font size approx 16, base spacing
previewCanvas.height = height * 16; // max font size approx 16
previewCanvas.style.display = 'block';
asciiPreview.style.display = 'none';
const ctx = previewCanvas.getContext('2d');
ctx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
ctx.textBaseline = 'top';
ctx.textAlign = 'left';
// Draw resized image to temp canvas to get colors
const tempCanvas = document.createElement('canvas');
tempCanvas.width = width;
tempCanvas.height = height;
const tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(img, 0, 0, width, height);
const imgData = tempCtx.getImageData(0, 0, width, height).data;
let yPos = 0;
for (let y = 0; y < height; y++) {
let xPos = 0;
let currentFontSize = getRandomInt(8, 16);
let charCountSinceChange = 0;
for (let x = 0; x < width; x++) {
const ch = lines[y][x];
if (ch === '\n') continue;
const char = ch === ' ' ? '\u00A0' : ch;
// Change font size only every fontSizeDelta chars
if (wildNeonEnabled && charCountSinceChange >= fontSizeDelta) {
currentFontSize = getRandomInt(8, 16);
charCountSinceChange = 0;
}
charCountSinceChange++;
ctx.font = `${currentFontSize}px ${customFontName}`;
// Get pixel color
const i = y * width + x;
let r = imgData[i * 4];
let g = imgData[i * 4 + 1];
let b = imgData[i * 4 + 2];
// Compute luminance for color modes
const lum = rgbToLuminance(r, g, b);
// Apply color mode
let [cr, cg, cb] = applyColorMode(r, g, b, lum, colorMode);
// Compose fillStyle
const fillStyle = `rgb(${Math.round(cr)},${Math.round(cg)},${Math.round(cb)})`;
ctx.fillStyle = fillStyle;
// Neon glow for wild neon mode
if (wildNeonEnabled) {
const neonColor = getRandomNeonColor();
if (neonGlowIntensity > 0) {
ctx.shadowColor = neonColor;
ctx.shadowBlur = neonGlowIntensity * 1.5;
} else {
ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0;
}
} else {
ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0;
}
ctx.fillText(char, xPos, yPos);
xPos += currentFontSize * 0.6;
}
yPos += 16;
}
}
// --- Main Generation Handler ---
async function handleGeneration() {
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
}
if (mediaType === 'none' || !imageLoader.files.length) {
setStatus('Please select an input file.');
return;
}
setUIState(true);
setStatus('Starting generation...');
sourceFrames = [];
try {
const startFile = imageLoader.files[0];
const endFile = imageLoaderEnd.files.length > 0 ? imageLoaderEnd.files[0] : null;
if (mediaType === 'tween') {
await processTween(startFile, endFile);
} else if (mediaType === 'video') {
await processVideo(startFile);
} else if (mediaType === 'image') {
await processSingleImage(startFile);
}
updateExportButtons();
} catch (error) {
console.error("Generation failed:", error);
setStatus(`Error: ${error.message}`);
} finally {
setUIState(false);
}
}
// --- Processing Functions ---
async function processSingleImage(file) {
setStatus('Processing image...');
const img = await loadImage(URL.createObjectURL(file));