Repository navigation
Expand file tree
/
Copy pathsocial-media-cropper.html
More file actions
1035 lines (951 loc) · 41.4 KB
/
Copy pathsocial-media-cropper.html
File metadata and controls
1035 lines (951 loc) · 41.4 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>
<head>
<meta charset="utf-8">
<title>Social Media Card Cropper</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css">
<style>
body {
font-family: system-ui, -apple-system, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f5f5f5;
color: #333;
}
.container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.drop-zone {
border: 2px dashed #ccc;
border-radius: 4px;
padding: 40px 20px;
text-align: center;
margin-bottom: 20px;
background: #fafafa;
cursor: pointer;
transition: all 0.2s ease;
}
.drop-zone:hover {
border-color: #999;
background: #f2f2f2;
}
.drop-zone.dragover {
border-color: #0066cc;
background: #e6f2ff;
}
.img-container {
max-width: 100%;
margin-bottom: 20px;
}
#image {
display: block;
max-width: 100%;
}
.preview-container {
margin-top: 20px;
padding: 16px;
background: #fafafa;
border-radius: 8px;
border: 1px solid #eee;
}
#preview {
width: 100%;
max-width: 600px;
margin: 0 auto;
display: block;
border-radius: 4px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.download-btn {
display: inline-block;
padding: 10px 20px;
background: #0066cc;
color: white;
text-decoration: none;
border-radius: 4px;
margin-top: 10px;
transition: background 0.2s;
font-weight: 500;
border: none;
cursor: pointer;
}
.download-btn.pending {
opacity: 0.6;
pointer-events: none;
}
.download-btn:hover {
background: #0052a3;
}
.hidden {
display: none;
}
.controls {
margin-bottom: 20px;
padding: 15px;
background: #f9f9f9;
border-radius: 6px;
border: 1px solid #eee;
}
.aspect-controls {
margin-bottom: 15px;
}
.zoom-controls {
display: flex;
align-items: center;
justify-content: center;
margin: 15px 0;
gap: 12px;
}
.control-btn {
background: #f0f0f0;
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px 12px;
cursor: pointer;
transition: all 0.2s;
font-weight: 500;
}
.control-btn:hover {
background: #e0e0e0;
border-color: #ccc;
}
.zoom-btn {
width: 52px;
height: 52px;
border-radius: 50%;
border: 2px solid #ccc;
background: #fff;
font-size: 24px;
font-weight: 700;
line-height: 1;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.15s;
color: #333;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.zoom-btn:hover {
background: #f0f0f0;
border-color: #999;
box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}
.zoom-btn:active, .zoom-btn.pressing {
background: #e0e0e0;
border-color: #888;
transform: scale(0.93);
box-shadow: 0 0 2px rgba(0,0,0,0.1);
}
.zoom-value {
min-width: 55px;
text-align: center;
font-weight: 600;
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.drag-mode-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 0;
margin: 12px 0;
}
.drag-mode-btn {
padding: 10px 18px;
border: 2px solid #ccc;
background: #fff;
cursor: pointer;
font-size: 14px;
font-weight: 500;
transition: all 0.15s;
color: #555;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
}
.drag-mode-btn:first-child {
border-radius: 8px 0 0 8px;
}
.drag-mode-btn:last-child {
border-radius: 0 8px 8px 0;
border-left: none;
}
.drag-mode-btn.active {
background: #0066cc;
border-color: #0066cc;
color: #fff;
}
.drag-mode-btn:not(.active):hover {
background: #f0f0f0;
}
.color-picker {
display: flex;
align-items: center;
margin-top: 15px;
}
#backgroundColor {
width: 40px;
height: 40px;
padding: 0;
border: 1px solid #ddd;
border-radius: 4px;
margin-left: 8px;
cursor: pointer;
}
.help-text {
font-size: 13px;
color: #666;
margin-top: 5px;
}
.options-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.option-group {
flex: 1;
min-width: 200px;
}
label {
font-weight: 500;
}
@media (max-width: 600px) {
.controls {
padding: 10px;
}
.options-container {
gap: 10px;
}
.zoom-btn {
width: 56px;
height: 56px;
font-size: 28px;
}
.drag-mode-btn {
padding: 12px 16px;
font-size: 14px;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Social Media Card Cropper</h1>
<p>Drop an image or click to select. Create perfect social media cards with custom backgrounds.</p>
<div class="controls">
<div class="options-container">
<div class="option-group">
<label>Aspect Ratio:</label>
<div class="aspect-controls">
<label style="margin-right: 10px; display: block; margin-top: 8px;">
<input type="radio" name="aspectRatio" value="2" checked> 2:1 (Twitter/LinkedIn)
</label>
<label style="margin-right: 10px; display: block; margin-top: 8px;">
<input type="radio" name="aspectRatio" value="1.91"> 1.91:1 (Facebook)
</label>
<label style="margin-right: 10px; display: block; margin-top: 8px;">
<input type="radio" name="aspectRatio" value="1.4"> 1.4:1 (Substack)
</label>
<label style="display: block; margin-top: 8px;">
<input type="radio" name="aspectRatio" value="1"> 1:1 (Instagram)
</label>
</div>
</div>
<div class="option-group">
<div class="color-picker">
<label for="backgroundColor">Background color:</label>
<input type="color" id="backgroundColor" value="#ffffff">
</div>
<div style="margin-top: 15px;">
<button id="resetBtn" class="control-btn">Reset Image</button>
</div>
</div>
<div class="option-group">
<label>Output format:</label>
<div class="aspect-controls">
<label style="margin-right: 10px; display: block; margin-top: 8px;">
<input type="radio" name="outputFormat" value="jpeg" checked> JPEG
</label>
<label style="display: block; margin-top: 8px;">
<input type="radio" name="outputFormat" value="webp"> WebP
</label>
<label style="display: block; margin-top: 8px;">
<input type="radio" name="outputFormat" value="avif"> AVIF
</label>
</div>
<div style="margin-top: 12px;">
<label for="quality">Quality (0–100):</label>
<input type="number" id="quality" min="0" max="100" step="1" value="90" style="width: 70px; margin-left: 6px;">
</div>
<div id="webpNote" class="help-text" hidden>This browser has no WebP encoder that respects the quality setting, so the @jsquash/webp encoder is loaded from jsdelivr the first time a WebP card is generated.</div>
<div id="avifNote" class="help-text" hidden>This browser has no AVIF encoder that respects the quality setting, so the @jsquash/avif encoder (3.5 MB) is loaded from jsdelivr the first time an AVIF card is generated. Encoding takes a few seconds.</div>
</div>
</div>
</div>
<div class="drop-zone" id="dropZone">
<div>
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" style="color: #999; margin-bottom: 10px;">
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"></path>
<line x1="16" y1="5" x2="22" y2="5"></line>
<line x1="19" y1="2" x2="19" y2="8"></line>
<circle cx="9" cy="9" r="2"></circle>
<path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"></path>
</svg>
</div>
Drop image here, click to select, or paste from clipboard
<div class="help-text">Supports JPG, PNG, GIF, and WebP formats</div>
<input type="file" id="fileInput" accept="image/*" class="hidden">
</div>
<div class="img-container">
<img id="image" class="hidden">
</div>
<div class="hidden" id="zoomControlsContainer">
<div class="drag-mode-controls">
<button id="dragMoveBtn" class="drag-mode-btn active">Move Image</button>
<button id="dragCropBtn" class="drag-mode-btn">Move Crop</button>
</div>
<div class="zoom-controls">
<button id="zoomOutBtn" class="zoom-btn" aria-label="Zoom out">−</button>
<span id="zoomValue" class="zoom-value">100%</span>
<button id="zoomInBtn" class="zoom-btn" aria-label="Zoom in">+</button>
</div>
</div>
<div class="preview-container hidden" id="previewContainer">
<h3>Preview</h3>
<img id="preview">
<div id="dimensionsInfo" style="text-align: center; margin-top: 10px; font-size: 14px; color: #666;"></div>
<div style="text-align: center; margin-top: 15px;">
<a href="#" id="downloadBtn" class="download-btn">Download Social Media Card</a>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>
<script>
let cropper = null;
let cropperData = null;
let zoomValue = 1;
let currentDragMode = 'move'; // 'move' = move image, 'crop' = move crop box
let userChangedBgColor = false; // tracks if user manually picked a color
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const backgroundColor = document.getElementById('backgroundColor');
const zoomInBtn = document.getElementById('zoomInBtn');
const zoomOutBtn = document.getElementById('zoomOutBtn');
const zoomValueDisplay = document.getElementById('zoomValue');
const resetBtn = document.getElementById('resetBtn');
const zoomControlsContainer = document.getElementById('zoomControlsContainer');
const dragMoveBtn = document.getElementById('dragMoveBtn');
const dragCropBtn = document.getElementById('dragCropBtn');
const image = document.getElementById('image');
const preview = document.getElementById('preview');
const previewContainer = document.getElementById('previewContainer');
const downloadBtn = document.getElementById('downloadBtn');
const qualityInput = document.getElementById('quality');
// --- Drag mode toggle ---
// Cropper.js stacks .cropper-crop-box on top of .cropper-drag-box.
// Touches inside the crop area always hit the crop box first, so
// dragMode('move') alone doesn't help on mobile. We toggle
// pointer-events on the crop box to let touches pass through to
// the image-drag layer when "Move Image" is active.
function setDragMode(mode) {
currentDragMode = mode;
const cropBox = document.querySelector('.cropper-crop-box');
if (mode === 'move') {
dragMoveBtn.classList.add('active');
dragCropBtn.classList.remove('active');
if (cropper) {
cropper.setDragMode('move');
}
if (cropBox) cropBox.style.pointerEvents = 'none';
} else {
dragCropBtn.classList.add('active');
dragMoveBtn.classList.remove('active');
if (cropper) {
cropper.setDragMode('none');
}
if (cropBox) cropBox.style.pointerEvents = 'auto';
}
}
dragMoveBtn.addEventListener('click', () => setDragMode('move'));
dragCropBtn.addEventListener('click', () => setDragMode('crop'));
// --- Press-and-hold continuous zoom ---
function setupContinuousButton(btn, actionFn) {
let holdTimer = null;
let holdInterval = null;
function startHold(e) {
e.preventDefault();
// Fire once immediately
actionFn();
btn.classList.add('pressing');
// After a short delay, start repeating
holdTimer = setTimeout(() => {
let speed = 60; // ms between repeats, starts moderate
let elapsed = 0;
holdInterval = setInterval(() => {
actionFn();
elapsed++;
// Accelerate after sustained hold
if (elapsed > 15 && speed > 30) {
clearInterval(holdInterval);
speed = 30;
holdInterval = setInterval(() => actionFn(), speed);
}
}, speed);
}, 300);
}
function stopHold(e) {
if (e) e.preventDefault();
btn.classList.remove('pressing');
if (holdTimer) { clearTimeout(holdTimer); holdTimer = null; }
if (holdInterval) { clearInterval(holdInterval); holdInterval = null; }
}
// Mouse events
btn.addEventListener('mousedown', startHold);
window.addEventListener('mouseup', stopHold);
// Touch events
btn.addEventListener('touchstart', startHold, { passive: false });
btn.addEventListener('touchend', stopHold, { passive: false });
btn.addEventListener('touchcancel', stopHold, { passive: false });
// Prevent context menu on long press
btn.addEventListener('contextmenu', (e) => e.preventDefault());
}
function doZoomIn() {
if (!cropper) return;
zoomValue = Math.min(zoomValue + 0.02, 3);
updateZoomDisplay();
cropper.zoomTo(zoomValue);
}
function doZoomOut() {
if (!cropper) return;
let zoomDecrement = 0.02;
if (zoomValue < 0.2) {
zoomDecrement = 0.005;
} else if (zoomValue < 0.5) {
zoomDecrement = 0.01;
}
zoomValue = Math.max(zoomValue - zoomDecrement, 0.01);
updateZoomDisplay();
cropper.zoomTo(zoomValue);
const canvasData = cropper.getCanvasData();
if (zoomValue < 0.3) {
const scaleFactor = zoomValue < 0.1 ? 0.98 : 0.99;
cropper.setCanvasData({
width: canvasData.width * scaleFactor,
height: canvasData.height * scaleFactor,
left: canvasData.left + (canvasData.width - canvasData.width * scaleFactor) / 2,
top: canvasData.top + (canvasData.height - canvasData.height * scaleFactor) / 2
});
}
}
setupContinuousButton(zoomInBtn, doZoomIn);
setupContinuousButton(zoomOutBtn, doZoomOut);
// --- Handle paste events ---
document.addEventListener('paste', (e) => {
e.preventDefault();
const items = (e.clipboardData || e.originalEvent.clipboardData).items;
for (const item of items) {
if (item.type.indexOf('image') === 0) {
const file = item.getAsFile();
handleFile(file);
break;
}
}
});
// --- Handle drag and drop ---
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('dragover');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('dragover');
handleFile(e.dataTransfer.files[0]);
});
// Handle click to select
dropZone.addEventListener('click', () => {
fileInput.click();
});
fileInput.addEventListener('change', (e) => {
if (e.target.files.length) {
handleFile(e.target.files[0]);
}
});
// Reset button
resetBtn.addEventListener('click', () => {
if (cropper) {
cropper.reset();
// Read the actual zoom ratio after reset
const canvasData = cropper.getCanvasData();
if (canvasData.naturalWidth) {
zoomValue = canvasData.width / canvasData.naturalWidth;
} else {
zoomValue = 1;
}
updateZoomDisplay();
setDragMode('move');
updatePreview();
}
});
// Listen for aspect ratio changes and update the cropper
document.querySelectorAll('input[name="aspectRatio"]').forEach(radio => {
radio.addEventListener('change', () => {
if (cropper) {
const currentZoom = zoomValue;
initCropper(true);
setTimeout(() => {
zoomValue = currentZoom;
updateZoomDisplay();
cropper.zoomTo(currentZoom);
}, 100);
}
});
});
// Listen for background color changes and update the preview
backgroundColor.addEventListener('input', () => {
userChangedBgColor = true;
});
backgroundColor.addEventListener('change', () => {
userChangedBgColor = true;
updatePreview();
});
function updateZoomDisplay() {
let displayValue = Math.round(zoomValue * 100);
if (zoomValue < 0.1) {
displayValue = (zoomValue * 100).toFixed(1);
}
zoomValueDisplay.textContent = `${displayValue}%`;
}
// --- Edge color detection ---
// Samples pixels along all four edges. If they're sufficiently
// uniform, returns the dominant color as a hex string; otherwise null.
function detectEdgeColor(img) {
const c = document.createElement('canvas');
const ctx = c.getContext('2d', { willReadFrequently: true });
c.width = img.naturalWidth;
c.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
const w = c.width, h = c.height;
if (w < 3 || h < 3) return null;
// Collect sample positions along all four edges
const step = Math.max(1, Math.floor(Math.max(w, h) / 40));
const samples = [];
for (let x = 0; x < w; x += step) {
samples.push([x, 0]); // top
samples.push([x, h - 1]); // bottom
}
for (let y = 0; y < h; y += step) {
samples.push([0, y]); // left
samples.push([w - 1, y]); // right
}
let rSum = 0, gSum = 0, bSum = 0;
const colors = [];
for (const [sx, sy] of samples) {
const d = ctx.getImageData(sx, sy, 1, 1).data;
colors.push([d[0], d[1], d[2]]);
rSum += d[0]; gSum += d[1]; bSum += d[2];
}
const n = colors.length;
const rAvg = rSum / n, gAvg = gSum / n, bAvg = bSum / n;
// Check how much each sample deviates from the average
const threshold = 30; // max average deviation per channel
let totalDev = 0;
for (const [r, g, b] of colors) {
totalDev += Math.abs(r - rAvg) + Math.abs(g - gAvg) + Math.abs(b - bAvg);
}
if (totalDev / n > threshold) return null;
// Convert average to hex
const toHex = (v) => Math.round(v).toString(16).padStart(2, '0');
return '#' + toHex(rAvg) + toHex(gAvg) + toHex(bAvg);
}
function handleFile(file) {
if (!file || !file.type.startsWith('image/')) {
alert('Please select a valid image file.');
return;
}
const reader = new FileReader();
reader.onload = (e) => {
image.src = e.target.result;
image.classList.remove('hidden');
zoomControlsContainer.classList.remove('hidden');
zoomValue = 1;
updateZoomDisplay();
setDragMode('move');
// Detect edge color once the image is decoded
const tempImg = new Image();
tempImg.onload = () => {
if (!userChangedBgColor) {
const edgeColor = detectEdgeColor(tempImg);
if (edgeColor) {
backgroundColor.value = edgeColor;
} else {
backgroundColor.value = '#ffffff';
}
}
initCropper();
};
tempImg.src = e.target.result;
};
reader.readAsDataURL(file);
}
function initCropper(preserveData = false) {
if (cropper) {
if (preserveData) {
cropperData = cropper.getData();
}
cropper.destroy();
}
const aspectRatioValue = document.querySelector('input[name="aspectRatio"]:checked').value;
const ratio = parseFloat(aspectRatioValue);
cropper = new Cropper(image, {
aspectRatio: ratio,
viewMode: 0,
dragMode: currentDragMode === 'move' ? 'move' : 'none',
autoCropArea: 0.9,
restore: false,
guides: true,
center: true,
highlight: false,
cropBoxMovable: true,
cropBoxResizable: true,
toggleDragModeOnDblclick: false,
minCropBoxWidth: 100,
minCropBoxHeight: 100,
// Disable Cropper.js built-in wheel zoom (we handle zoom via buttons)
zoomOnWheel: false,
// Disable Cropper.js touch zoom - we intercept pinch ourselves
zoomOnTouch: false,
ready: function() {
// Sync zoomValue to the actual ratio Cropper.js computed
// so the first +/- click doesn't jump
const canvasData = cropper.getCanvasData();
if (canvasData.naturalWidth) {
zoomValue = canvasData.width / canvasData.naturalWidth;
updateZoomDisplay();
}
if (preserveData && cropperData) {
setTimeout(() => {
cropper.setData(cropperData);
}, 50);
}
// Apply pointer-events for current drag mode now that
// the crop box element exists in the DOM
const cropBox = document.querySelector('.cropper-crop-box');
if (cropBox) {
cropBox.style.pointerEvents = currentDragMode === 'move' ? 'none' : 'auto';
}
updatePreview();
// Install custom pinch-zoom handler on the cropper container
installPinchZoom();
},
zoom: function(e) {
zoomValue = e.detail.ratio;
updateZoomDisplay();
},
crop: updatePreview
});
}
// --- Custom pinch-zoom handler ---
// This ensures single-touch drag moves image/crop as expected,
// and only two-finger pinch triggers zoom.
function installPinchZoom() {
const cropperContainer = document.querySelector('.cropper-container');
if (!cropperContainer) return;
let pinchStartDist = 0;
let pinchStartZoom = 1;
function getTouchDistance(t1, t2) {
const dx = t1.clientX - t2.clientX;
const dy = t1.clientY - t2.clientY;
return Math.sqrt(dx * dx + dy * dy);
}
cropperContainer.addEventListener('touchstart', (e) => {
if (e.touches.length === 2) {
// Starting a pinch - record baseline
pinchStartDist = getTouchDistance(e.touches[0], e.touches[1]);
pinchStartZoom = zoomValue;
}
}, { passive: true });
cropperContainer.addEventListener('touchmove', (e) => {
if (e.touches.length === 2 && pinchStartDist > 0) {
e.preventDefault(); // prevent page zoom
const currentDist = getTouchDistance(e.touches[0], e.touches[1]);
const scale = currentDist / pinchStartDist;
const newZoom = Math.max(0.01, Math.min(3, pinchStartZoom * scale));
zoomValue = newZoom;
updateZoomDisplay();
cropper.zoomTo(newZoom);
}
}, { passive: false });
cropperContainer.addEventListener('touchend', () => {
pinchStartDist = 0;
}, { passive: true });
}
// --- WebP and AVIF encoding ---
// Browsers that cannot encode a format from a canvas silently return
// a PNG instead: Safari (desktop and iOS) cannot do WebP, and most
// browsers cannot do AVIF. Feature-detect each format once, and only
// when native encoding is missing (or ignores quality) load a jSquash
// wasm encoder (Squoosh's libwebp or libavif) from jsdelivr the first
// time that format is actually requested.
const JSQUASH_WEBP_ENCODE_URL = 'https://cdn.jsdelivr.net/npm/@jsquash/webp@1.5.0/encode.js/+esm';
const JSQUASH_AVIF_ENCODE_URL = 'https://cdn.jsdelivr.net/npm/@jsquash/avif@2.1.1/encode.js/+esm';
const OUTPUT_FORMATS = {
jpeg: { mime: 'image/jpeg', extension: 'jpg', label: 'JPEG' },
webp: { mime: 'image/webp', extension: 'webp', label: 'WebP' },
avif: { mime: 'image/avif', extension: 'avif', label: 'AVIF' },
};
const nativeEncodeSupportPromises = {};
let jsquashWebpPromise = null;
// A native encoder is only used if it produces the requested format
// and honours the quality setting. Mobile Safari encodes AVIF but
// ignores quality, which made every card the same (huge) file.
function canvasCanEncode(mime) {
if (!nativeEncodeSupportPromises[mime]) {
nativeEncodeSupportPromises[mime] = (async () => {
const canvas = document.createElement('canvas');
canvas.width = 64;
canvas.height = 64;
if (!canvas.toBlob) return false;
// Noise, so that a lower quality has detail to throw away.
const ctx = canvas.getContext('2d');
const noise = ctx.createImageData(64, 64);
for (let i = 0; i < noise.data.length; i++) {
noise.data[i] = i % 4 === 3 ? 255 : Math.random() * 256;
}
ctx.putImageData(noise, 0, 0);
const encodeAt = quality => new Promise(resolve => {
try {
canvas.toBlob(resolve, mime, quality);
} catch (err) {
resolve(null);
}
});
const [low, high] = await Promise.all([encodeAt(0.2), encodeAt(0.9)]);
return Boolean(low && high && low.type === mime && high.type === mime && low.size !== high.size);
})();
}
return nativeEncodeSupportPromises[mime];
}
function loadJsquashWebpEncoder() {
if (!jsquashWebpPromise) {
// Call init() explicitly: encode() would otherwise cache a failed
// wasm load for the lifetime of the page, so a flaky connection
// could never be retried.
jsquashWebpPromise = import(JSQUASH_WEBP_ENCODE_URL).then(async mod => {
await mod.init();
return mod.default;
});
jsquashWebpPromise.catch(() => { jsquashWebpPromise = null; });
}
return jsquashWebpPromise;
}
async function encodeWebpWithWasm(canvas, quality) {
const imageData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
const encode = await loadJsquashWebpEncoder();
const buffer = await encode(imageData, { quality: Math.round(quality * 100) });
return new Blob([buffer], { type: 'image/webp' });
}
// The AVIF encoder takes seconds per image, so unlike WebP it runs in
// a module worker to keep the page responsive.
const AVIF_WORKER_SOURCE = `
let encoderPromise = null;
self.onmessage = async (e) => {
const { data, width, height, quality } = e.data;
try {
if (!encoderPromise) {
encoderPromise = import(${JSON.stringify(JSQUASH_AVIF_ENCODE_URL)}).then(async (mod) => {
await mod.init();
return mod.default;
});
}
const encode = await encoderPromise;
const buffer = await encode({ data, width, height }, { quality });
self.postMessage({ buffer }, [buffer]);
} catch (err) {
self.postMessage({ error: String((err && err.message) || err) });
}
};
`;
let avifWorkerUrl = null;
let avifWorker = null;
// Encodes run one at a time, in the order they were requested.
let avifQueue = Promise.resolve();
function runAvifWorkerJob(imageData, quality) {
if (!avifWorker) {
avifWorkerUrl = avifWorkerUrl || URL.createObjectURL(new Blob([AVIF_WORKER_SOURCE], { type: 'text/javascript' }));
avifWorker = new Worker(avifWorkerUrl, { type: 'module' });
}
const worker = avifWorker;
return new Promise((resolve, reject) => {
const fail = message => {
// Start from a fresh worker next time, so a failed encoder
// download can be retried instead of being cached for the
// life of the page.
worker.terminate();
if (avifWorker === worker) avifWorker = null;
reject(new Error(message));
};
worker.onmessage = e => {
if (e.data.error !== undefined) fail(e.data.error);
else resolve(new Blob([e.data.buffer], { type: 'image/avif' }));
};
worker.onerror = e => {
e.preventDefault();
fail(e.message || 'AVIF encoder worker failed');
};
const { data, width, height } = imageData;
worker.postMessage({ data, width, height, quality }, [data.buffer]);
});
}
// The pixels are read when the job starts, so the canvas must not be
// drawn on again until the returned promise settles. A job whose
// `signal` has been aborted by then is skipped.
function encodeAvifWithWasm(canvas, quality, signal) {
const job = avifQueue.then(() => {
if (signal && signal.aborted) throw new DOMException('AVIF encode cancelled', 'AbortError');
const imageData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
return runAvifWorkerJob(imageData, Math.round(quality * 100));
});
avifQueue = job.catch(() => {});
return job;
}
const WASM_ENCODERS = {
'image/webp': encodeWebpWithWasm,
'image/avif': encodeAvifWithWasm,
};
// Encode a canvas as a Blob. `quality` is 0..1 as for canvas.toBlob.
async function canvasToBlob(canvas, mime, quality, signal) {
const wasmEncode = WASM_ENCODERS[mime];
if (wasmEncode && !(await canvasCanEncode(mime))) {
return wasmEncode(canvas, quality, signal);
}
return new Promise((resolve, reject) => {
canvas.toBlob(blob => {
if (blob && blob.type === mime) resolve(blob);
else reject(new Error(`Browser could not encode ${mime}`));
}, mime, quality);
});
}
canvasCanEncode('image/webp').then(supported => {
document.getElementById('webpNote').hidden = supported;
});
canvasCanEncode('image/avif').then(supported => {
document.getElementById('avifNote').hidden = supported;
});
function selectedOutputFormat() {
const value = document.querySelector('input[name="outputFormat"]:checked').value;
return OUTPUT_FORMATS[value] || OUTPUT_FORMATS.jpeg;
}
document.querySelectorAll('input[name="outputFormat"]').forEach(radio => {
radio.addEventListener('change', updatePreview);
});
// Encoder quality as 0..1, from the 0-100 input. Applies to JPEG, WebP
// and AVIF; the preview re-renders live as the value is edited.
function selectedQuality() {
const value = parseInt(qualityInput.value, 10);
if (Number.isNaN(value)) return 0.9;
return Math.max(0, Math.min(100, value)) / 100;
}
qualityInput.addEventListener('input', updatePreview);
qualityInput.addEventListener('change', () => {
// Normalise out-of-range or blank values once editing finishes.
qualityInput.value = Math.round(selectedQuality() * 100);
updatePreview();
});
// The download file is encoded asynchronously (WebP in Safari and
// AVIF in most browsers go through wasm), debounced so dragging the
// crop box does not queue up a full-size encode for every
// intermediate position. A slow AVIF encode that has not started yet
// is skipped once a newer one is scheduled.
let downloadGeneration = 0;
let downloadTimer = null;
let downloadUrl = null;
let downloadAbortController = null;
function scheduleDownloadEncode(canvas, format, quality, filename) {
const generation = ++downloadGeneration;
clearTimeout(downloadTimer);
if (downloadAbortController) downloadAbortController.abort();
downloadAbortController = new AbortController();
const { signal } = downloadAbortController;
downloadBtn.classList.add('pending');
downloadBtn.textContent = `Preparing ${format.label}…`;
downloadBtn.removeAttribute('href');
downloadBtn.removeAttribute('download');
downloadTimer = setTimeout(() => {
canvasToBlob(canvas, format.mime, quality, signal).then(blob => {
if (generation !== downloadGeneration) return;
if (downloadUrl) URL.revokeObjectURL(downloadUrl);
downloadUrl = URL.createObjectURL(blob);
preview.src = downloadUrl;
downloadBtn.href = downloadUrl;
downloadBtn.download = filename;
downloadBtn.classList.remove('pending');
downloadBtn.textContent = `Download Social Media Card (${format.label} q${Math.round(quality * 100)}, ${(blob.size / 1024).toFixed(0)} KB)`;
}, err => {
if (generation !== downloadGeneration) return;
console.error(`${format.label} encoding failed`, err);
downloadBtn.classList.remove('pending');
downloadBtn.textContent = `Could not create ${format.label}: ${err.message}`;
});
}, 150);
}
function updatePreview() {
if (!cropper) return;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const aspectRatioValue = document.querySelector('input[name="aspectRatio"]:checked').value;
const ratio = parseFloat(aspectRatioValue);
if (ratio === 2) {
canvas.width = 1200;
canvas.height = 600;
} else if (ratio === 1.91) {
canvas.width = 1200;
canvas.height = 628;
} else if (ratio === 1.4) {
canvas.width = 1400;
canvas.height = 1000;
} else if (ratio === 1) {
canvas.width = 1080;
canvas.height = 1080;
} else {
canvas.width = 1200;
canvas.height = 1200 / ratio;