-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
750 lines (652 loc) · 26.2 KB
/
Copy pathindex.html
File metadata and controls
750 lines (652 loc) · 26.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="author" content="Christopher Brewer [https://github.com/cgcb]">
<meta name="description"
content="A benchmark tool for comparing image resizing performance using OffscreenCanvas with Web Workers vs standard Canvas">
<title>Canvas Image Resize Benchmark</title>
<!-- Bootstrap 5 CSS & Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
<style>
samp {
white-space: pre-wrap;
font-size: 0.8rem;
display: block;
}
#output {
overflow: auto;
column-count: 3;
column-gap: 20px;
}
#results {
overflow: auto;
}
@media (max-width: 768px) {
#output {
column-count: 1;
}
}
@media (min-width: 769px) and (max-width: 992px) {
#output {
column-count: 2;
}
}
.form-control-sm,
.form-select-sm,
.form-range {
min-width: 100px;
}
.form-range::-webkit-slider-thumb {
background-color: #0d6efd;
}
.form-range::-webkit-slider-runnable-track {
background-color: #dee2e6;
}
.form-range::-moz-range-thumb {
background-color: #0d6efd;
}
.form-range::-moz-range-track {
background-color: #dee2e6;
}
.card-header {
font-weight: bold;
}
.form-label {
font-size: 0.875rem;
color: #6c757d;
}
.slider-label {
min-width: 80px;
display: inline-block;
}
.grid-item {
position: relative;
}
.grid-item img {
width: 100%;
height: 250px;
object-fit: cover;
cursor: pointer;
}
.overlay {
position: absolute;
bottom: 0;
width: 100%;
background: rgba(0, 0, 0, 0.4);
color: white;
padding: 2px;
text-align: center;
font-size: 1rem;
}
#lightbox {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.8);
justify-content: center;
align-items: center;
z-index: 1050;
}
#lightbox.active {
display: flex;
}
#lightbox img {
max-width: none;
max-height: none;
}
#lightbox .close-btn {
position: absolute;
top: 15px;
right: 15px;
color: white;
font-size: 30px;
cursor: pointer;
z-index: 1060;
}
/* Custom styling for Buy Me A Coffee button */
.bmc-btn-container {
transform: scale(0.7) !important;
transform-origin: center center !important;
}
@media (max-width: 576px) {
.slider-label {
min-width: 60px;
}
}
</style>
</head>
<body>
<div class="container mt-4">
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="fs-2">Canvas Image Resize Benchmark</h1>
</div>
</div>
<div class="card mb-3" id="capabilities-panel">
<div class="card-header">Capabilities</div>
<div class="card-body bg-light text-center">
<span class="me-3 me-md-5 d-inline-block" id="browser-info"><i
class="bi bi-browser-chrome text-primary"></i> Detecting browser...</span>
<span class="me-3 me-md-5 d-inline-block" id="webworker-support"><i
class="bi bi-hourglass-split text-warning"></i> Web Workers</span>
<span class="me-3 me-md-5 d-inline-block" id="canvas-support"><i
class="bi bi-hourglass-split text-warning"></i> Canvas</span>
<span class="me-3 me-md-5 d-inline-block" id="offscreencanvas-support"><i
class="bi bi-hourglass-split text-warning"></i> OffscreenCanvas</span>
<span class="me-3 me-md-5 d-inline-block" id="convertToBlob-support"><i
class="bi bi-hourglass-split text-warning"></i> convertToBlob</span>
</div>
</div>
</div> <!-- Close top container -->
<div class="container mb-3">
<!-- Form controls -->
<div class="card">
<div class="card-header">Processing Options</div>
<form id="benchmarkForm" class="card-body bg-light">
<div class="row g-3 align-items-end" id="controls">
<div class="col-md-3">
<label for="files" class="form-label">Select images (1–200):</label>
<input id="files" type="file" multiple accept="image/*" class="form-control form-control-sm"
required />
</div>
<div class="col-md-2">
<label class="form-label"><span class="slider-label">Process:</span> <span id="countDisplay"
class="fw-bold">All</span></label>
<input id="count" type="range" class="form-range" min="1" max="200" value="200" />
</div>
<div class="col-md-2">
<label class="form-label"><span class="slider-label">Quality:</span> <span id="qualityDisplay"
class="fw-bold">65%</span></label>
<input id="quality" type="range" class="form-range" min="0" max="100" step="5" value="65" />
</div>
<div class="col-md-2">
<label class="form-label"><span class="slider-label">Resize to:</span> <span id="maxDimDisplay"
class="fw-bold">1000px</span></label>
<input id="maxDim" type="range" class="form-range" min="100" max="1200" step="50" value="1000" />
</div>
<div class="col-md-2">
<label for="concurrency" class="form-label"><span class="slider-label">Workers:</span> <span
id="concurrencyDisplay" class="fw-bold">16</span></label>
<input id="concurrency" type="range" class="form-range" min="1" max="32" step="1" value="16" />
</div>
<div class="col-md-1">
<button type="submit" id="run" class="btn btn-primary btn-sm w-100 text-nowrap">Run</button>
</div>
</div>
</form>
</div>
</div> <!-- Close form container -->
<div class="container mb-3">
<!-- Progress bar with anchor for scrolling -->
<div id="progressAnchor"></div>
<div class="progress mb-4 d-none" id="progressContainer">
<div class="progress-bar progress-bar-striped progress-bar-animated" id="progressBar" role="progressbar"
style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div> <!-- Close progress container -->
<main class="container mb-4">
<!-- Full-width output with columns -->
<div class="row">
<div class="col-md-9 mb-3 mb-md-0">
<div class="card h-100">
<div class="card-header">Log</div>
<div class="card-body">
<samp id="output"></samp>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card h-100">
<div class="card-header">Results</div>
<div class="card-body">
<samp id="results"></samp>
</div>
</div>
</div>
</div>
</main> <!-- Close output container -->
<div class="container mb-4">
<div id="grid" class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4"></div>
<div id="lightbox">
<div class="close-btn">×</div>
</div>
</div> <!-- Close lightbox grid container -->
<footer class="container mb-4 border-top pt-3">
<div class="d-flex flex-column flex-md-row justify-content-between align-items-center">
<p class="fw-lighter mb-3 mb-md-2 fs-6 text-center text-md-start text-muted mx-auto mx-md-0 ms-md-4">Version
1.0 by Chris Brewer <a class="fw-lighter ms-2 ms-md-4" href="https://github.com/cgcb"><i
class="bi bi-github"></i> https://github.com/cgcb</a></p>
<div class="text-center text-md-end mx-auto mx-md-0">
<script type="text/javascript" src="https://cdnjs.buymeacoffee.com/1.0.0/button.prod.min.js"
data-name="bmc-button" data-slug="cbrew" data-color="#FFDD00" data-emoji="" data-font="Cookie"
data-text="Buy me a pizza" data-outline-color="#000000" data-font-color="#000000"
data-coffee-color="#ffffff"></script>
</div>
</div>
</footer>
<!-- Bootstrap 5 JS Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Detect browser type
const isFirefox = navigator.userAgent.includes('Firefox');
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
const isChrome = /chrome|chromium/i.test(navigator.userAgent) && !isSafari;
const isEdge = /edg/i.test(navigator.userAgent);
// Set file input accept types
const fileInput = document.getElementById('files');
const acceptTypes = ['image/jpeg', 'image/png', 'image/webp'];
if (isSafari) acceptTypes.push('image/heic', 'image/heif');
fileInput.setAttribute('accept', acceptTypes.join(','));
// Feature detection function - enhanced for more reliable capability detection
function detectCapabilities() {
// Browser detection
const browserInfo = document.getElementById('browser-info');
if (isFirefox) {
browserInfo.innerHTML = '<i class="bi bi-browser-firefox text-warning"></i> Firefox';
} else if (isSafari) {
browserInfo.innerHTML = '<i class="bi bi-browser-safari text-primary"></i> Safari';
} else if (isEdge) {
browserInfo.innerHTML = '<i class="bi bi-browser-edge text-primary"></i> Edge';
} else if (isChrome) {
browserInfo.innerHTML = '<i class="bi bi-browser-chrome text-success"></i> Chrome';
} else {
browserInfo.innerHTML = '<i class="bi bi-browser-chrome text-secondary"></i> Other Browser';
}
// Canvas support
const canvasSupport = document.getElementById('canvas-support');
const hasCanvas = typeof HTMLCanvasElement !== 'undefined' &&
typeof HTMLCanvasElement.prototype.toBlob === 'function';
if (hasCanvas) {
canvasSupport.innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Canvas';
} else {
canvasSupport.innerHTML = '<i class="bi bi-x-circle-fill text-danger"></i> Canvas';
}
// OffscreenCanvas support
const offscreenSupport = document.getElementById('offscreencanvas-support');
const hasOffscreenCanvas = typeof OffscreenCanvas !== 'undefined';
if (hasOffscreenCanvas) {
offscreenSupport.innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> OffscreenCanvas';
} else {
offscreenSupport.innerHTML = '<i class="bi bi-x-circle-fill text-danger"></i> OffscreenCanvas';
}
// convertToBlob support
const convertSupport = document.getElementById('convertToBlob-support');
// Enhanced detection - check both API existence and runtime capability
let hasConvertToBlob = false;
if (hasOffscreenCanvas) {
try {
const testCanvas = new OffscreenCanvas(1, 1);
hasConvertToBlob = typeof testCanvas.convertToBlob === 'function';
} catch (e) {
console.warn('Error testing OffscreenCanvas.convertToBlob:', e);
hasConvertToBlob = false;
}
}
if (hasConvertToBlob) {
convertSupport.innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> convertToBlob';
} else {
convertSupport.innerHTML = '<i class="bi bi-x-circle-fill text-danger"></i> convertToBlob';
}
// Web Workers support
const workerSupport = document.getElementById('webworker-support');
const hasWebWorkers = typeof Worker !== 'undefined';
if (hasWebWorkers) {
workerSupport.innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Web Workers';
} else {
workerSupport.innerHTML = '<i class="bi bi-x-circle-fill text-danger"></i> Web Workers';
}
return {
hasCanvas,
hasOffscreenCanvas,
hasConvertToBlob,
hasWebWorkers,
isFirefox,
isSafari,
isChrome,
isEdge
};
}
// Run capability detection on page load
const capabilities = detectCapabilities();
// Helper function to determine processing strategy based on capabilities
function getProcessingStrategy() {
if (capabilities.hasOffscreenCanvas && capabilities.hasConvertToBlob && capabilities.hasWebWorkers) {
return {
type: 'parallel',
method: 'OffscreenCanvas.convertToBlob',
processor: 'worker'
};
} else if (capabilities.hasCanvas) {
const reason = !capabilities.hasOffscreenCanvas ? 'OffscreenCanvas not supported' :
!capabilities.hasConvertToBlob ? 'convertToBlob not supported' :
!capabilities.hasWebWorkers ? 'Web Workers not supported' :
'Unknown compatibility issue';
return {
type: 'serial',
method: 'Canvas.toBlob',
reason: reason,
processor: 'main-thread'
};
} else {
return {
type: 'unsupported',
error: 'This browser lacks basic Canvas.toBlob support required for image processing'
};
}
}
let originalSizes = [], newSizes = [], blobsArr = [];
// Track image blob URLs for cleanup
let imageBlobURLs = [];
const workerCode = `self.onmessage = async ({data:{file,quality,maxDim,index}}) => {
try {
const t0 = performance.now();
const img = await createImageBitmap(file);
let w = img.width, h = img.height;
if (w > h ? w > maxDim : h > maxDim) {
const scale = maxDim / (w > h ? w : h);
w = Math.round(w * scale);
h = Math.round(h * scale);
}
const canvas = new OffscreenCanvas(w, h);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
let blob;
try {
blob = await canvas.convertToBlob({type:'image/jpeg', quality: quality/100});
} catch (e) {
// If convertToBlob fails at runtime, communicate the error back
self.postMessage({error: true, errorMsg: 'OffscreenCanvas.convertToBlob failed: ' + e.message, index});
return;
}
const duration = performance.now() - t0;
self.postMessage({duration, size: blob.size, index, blob});
} catch (e) {
// Handle any other errors that might occur during processing
self.postMessage({error: true, errorMsg: 'Worker error: ' + e.message, index});
}
};`;
// Create a persistent blob URL for the worker code that won't be revoked between test runs
const workerBlobURL = URL.createObjectURL(new Blob([workerCode], { type: 'application/javascript' }));
const countInput = document.getElementById('count'), countDisplay = document.getElementById('countDisplay');
const qualityInput = document.getElementById('quality'), qualityDisplay = document.getElementById('qualityDisplay');
const maxDimInput = document.getElementById('maxDim'), maxDimDisplay = document.getElementById('maxDimDisplay');
const concurrencyInput = document.getElementById('concurrency'), concurrencyDisplay = document.getElementById('concurrencyDisplay');
countInput.oninput = _ => countDisplay.textContent = countInput.value;
qualityInput.oninput = _ => qualityDisplay.textContent = qualityInput.value + '%';
maxDimInput.oninput = _ => maxDimDisplay.textContent = maxDimInput.value + 'px';
concurrencyInput.oninput = _ => concurrencyDisplay.textContent = concurrencyInput.value;
function log(msg) {
const out = document.getElementById('output');
out.textContent += msg + '\n';
}
function logResults(results) {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = '';
results.forEach(msg => {
const line = document.createElement('div');
line.textContent = msg;
resultsDiv.appendChild(line);
});
}
// Clean up any previously created image blob URLs
function cleanupImageBlobURLs() {
// Revoke all previously created image blob URLs
imageBlobURLs.forEach(url => {
try {
URL.revokeObjectURL(url);
} catch (e) {
console.warn('Error revoking URL:', e);
}
});
imageBlobURLs = []; // Reset the tracking array
}
function showGrid() {
const grid = document.getElementById('grid');
grid.innerHTML = '';
// Clean up any previous image blob URLs before creating new ones
cleanupImageBlobURLs();
originalSizes.forEach((orig, i) => {
const blob = blobsArr[i];
// Make sure we have a valid blob before creating a URL
if (!blob) {
console.warn(`Missing blob data for image ${i}`);
return; // Skip this image
}
const url = URL.createObjectURL(blob);
// Track this URL for later cleanup
imageBlobURLs.push(url);
const col = document.createElement('div'); col.className = 'col';
const item = document.createElement('div'); item.className = 'grid-item card h-100';
const img = document.createElement('img');
img.src = url;
img.className = 'card-img-top';
img.addEventListener('click', () => {
const lb = document.getElementById('lightbox');
// Clear any existing images but keep the close button
Array.from(lb.children).forEach(child => {
if (!child.classList.contains('close-btn')) {
child.remove();
}
});
const imgEl = document.createElement('img');
imgEl.src = url; // This reuses the same Object URL from the thumbnail
lb.appendChild(imgEl);
lb.classList.add('active');
});
const overlay = document.createElement('div'); overlay.className = 'overlay';
const percent = (((orig - newSizes[i]) / orig) * 100).toFixed(1);
overlay.textContent = `${(orig / 1024).toFixed(1)} KB → ${(newSizes[i] / 1024).toFixed(1)} KB (${percent}% saved)`;
item.append(img, overlay);
col.append(item);
grid.append(col);
});
}
// Setup lightbox close functionality with resource cleanup
document.getElementById('lightbox').addEventListener('click', function (e) {
if (e.target === this || e.target.classList.contains('close-btn')) {
this.classList.remove('active');
// Note: We don't revoke URLs here because the same URLs are used by the grid thumbnails
// Those URLs will be properly cleaned up when a new set of images is processed
}
});
async function runTest(allFiles, workersCount, quality) {
// Clean up previous image blob URLs before starting a new test
cleanupImageBlobURLs();
originalSizes = []; newSizes = []; blobsArr = [];
document.getElementById('output').textContent = '';
document.getElementById('grid').innerHTML = '';
document.getElementById('results').innerHTML = '';
// Show progress bar
const progressContainer = document.getElementById('progressContainer');
const progressBar = document.getElementById('progressBar');
progressContainer.classList.remove('d-none');
progressBar.style.width = '0%';
progressBar.setAttribute('aria-valuenow', '0');
// We don't need to scroll here since we already scrolled before calling runTest
const files = allFiles.filter(f => f.type.startsWith('image/') && (isSafari || !/image\/(heic|heif)/.test(f.type)));
if (files.length < allFiles.length) log(`Skipped ${allFiles.length - files.length} unsupported files.`);
const maxDim = parseInt(maxDimInput.value, 10);
// Get the appropriate processing strategy based on browser capabilities
const strategy = getProcessingStrategy();
// Choose and log the processing method based on selected strategy
if (strategy.type === 'parallel') {
log(`Processing ${files.length} files via ${strategy.method} with ${workersCount} workers in parallel.`);
log('--------');
} else if (strategy.type === 'serial') {
log(`Processing ${files.length} files via ${strategy.method} on main thread (${strategy.reason}).`);
log('--------');
} else {
log(`Error: ${strategy.error}`);
// Hide progress bar as we can't proceed
progressContainer.classList.add('d-none');
return; // Exit the function as we can't process images
}
// Use simplified condition based on strategy
const canOffscreen = strategy.type === 'parallel';
let originalTotal = 0, resizedTotal = 0;
const durations = [];
const tStart = performance.now();
// Setup progress tracking
let completed = 0;
if (!canOffscreen) {
for (let i = 0; i < files.length; i++) {
const f = files[i]; originalSizes.push(f.size); originalTotal += f.size;
const t0 = performance.now();
const img = await createImageBitmap(f);
let w = img.width, h = img.height;
if (w > h ? w > maxDim : h > maxDim) {
const scale = maxDim / (w > h ? w : h);
w = Math.round(w * scale); h = Math.round(h * scale);
}
const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h;
const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, w, h);
const blobObj = await new Promise(res => canvas.toBlob(res, 'image/jpeg', quality / 100));
const dur = performance.now() - t0; durations.push(dur); resizedTotal += blobObj.size; newSizes.push(blobObj.size); blobsArr.push(blobObj);
log(`Image ${i + 1}/${files.length}: ${dur.toFixed(1)} ms`);
// Update progress
completed++;
const progress = Math.round((completed / files.length) * 100);
progressBar.style.width = `${progress}%`;
progressBar.setAttribute('aria-valuenow', progress);
}
} else {
const workers = Array.from({ length: workersCount }, () => new Worker(workerBlobURL));
const buckets = Array.from({ length: workersCount }, () => []);
files.forEach((f, i) => buckets[i % workersCount].push({ file: f, index: i }));
await Promise.all(buckets.map((bucket, wIdx) => (async () => {
const w = workers[wIdx];
for (const { file, index } of bucket) {
originalSizes[index] = file.size; originalTotal += file.size;
const result = await new Promise(res => {
const handler = ({ data }) => { w.removeEventListener('message', handler); res(data); };
w.addEventListener('message', handler);
w.postMessage({ file, quality, maxDim, index });
});
// Check for errors reported by the worker
if (result.error) {
log(`Error processing image ${index + 1}/${files.length}: ${result.errorMsg}`);
// Fall back to main thread processing for this image if there's an error
try {
const t0 = performance.now();
const img = await createImageBitmap(file);
let w = img.width, h = img.height;
if (w > h ? w > maxDim : h > maxDim) {
const scale = maxDim / (w > h ? w : h);
w = Math.round(w * scale); h = Math.round(h * scale);
}
const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h;
const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, w, h);
const blobObj = await new Promise(res => canvas.toBlob(res, 'image/jpeg', quality / 100));
const dur = performance.now() - t0;
durations.push(dur); resizedTotal += blobObj.size;
newSizes[index] = blobObj.size; blobsArr[index] = blobObj;
log(`Image ${index + 1}/${files.length}: ${dur.toFixed(1)} ms (fallback to main thread)`);
} catch (e) {
log(`Failed to process image ${index + 1} even with fallback: ${e.message}`);
}
} else {
const { duration, size, blob, index: idx } = result;
durations.push(duration); resizedTotal += size; newSizes[idx] = size; blobsArr[idx] = blob;
log(`Image ${idx + 1}/${files.length}: ${duration.toFixed(1)} ms`);
}
// Update progress
completed++;
const progress = Math.round((completed / files.length) * 100);
progressBar.style.width = `${progress}%`;
progressBar.setAttribute('aria-valuenow', progress);
}
})()));
// Terminate all workers
workers.forEach(w => w.terminate());
}
const totalTime = performance.now() - tStart;
const sum = durations.reduce((a, b) => a + b, 0);
const avg = (sum / durations.length).toFixed(1);
const min = Math.min(...durations).toFixed(1);
const max = Math.max(...durations).toFixed(1);
const avgOrigKB = (originalTotal / durations.length / 1024).toFixed(1);
const avgReszKB = (resizedTotal / durations.length / 1024).toFixed(1);
// Calculate parallelization metrics if using workers
let parallelFactor = 1;
let parallelEfficiencyMsg = "";
if (canOffscreen && workersCount > 1 && files.length > 1) {
parallelFactor = (sum / totalTime).toFixed(1);
parallelEfficiencyMsg = `Parallel Speedup: ${parallelFactor}x`;
}
// Update progress bar to complete
progressBar.style.width = '100%';
progressBar.setAttribute('aria-valuenow', '100');
progressBar.classList.remove('progress-bar-animated');
progressBar.classList.add('bg-success');
// Add a delay before hiding progress bar to show completion
setTimeout(() => {
progressContainer.classList.add('d-none');
progressBar.classList.remove('bg-success');
progressBar.classList.add('progress-bar-animated');
}, 800);
// Calculate savings percentage
const savingsPercent = ((originalTotal - resizedTotal) / originalTotal * 100).toFixed(1);
// Show results in separate column
const results = [
`Elapsed time: ${totalTime.toFixed(1)} ms`,
`Cumulative: ${sum.toFixed(1)} ms`,
`Average time: ${avg} ms`,
`Min time: ${min} ms`,
`Max time: ${max} ms`
];
// Add parallel efficiency information if applicable (after max time)
if (parallelEfficiencyMsg) {
results.push(parallelEfficiencyMsg);
}
// Add space and then image statistics
results.push('');
results.push(`Avg original: ${avgOrigKB} KB`);
results.push(`Avg resized: ${avgReszKB} KB`);
results.push(`Total savings: ${savingsPercent}%`);
logResults(results);
document.getElementById('output').scrollTop = document.getElementById('output').scrollHeight;
showGrid();
}
document.getElementById('benchmarkForm').onsubmit = (event) => {
// Prevent the default form submission behavior
event.preventDefault();
const all = Array.from(document.getElementById('files').files);
const count = Math.min(all.length, parseInt(countInput.value, 10));
const subset = all.slice(0, count);
const wc = Math.min(subset.length, parseInt(document.getElementById('concurrency').value, 10));
const q = parseInt(qualityInput.value, 10);
// Get the button's position for reference
const runButton = document.getElementById('run');
// Force scroll to the anchor element
document.getElementById('progressAnchor').scrollIntoView({
behavior: 'auto', // Using 'auto' instead of 'smooth' for more immediate effect
block: 'center'
});
// Run the test after a very short delay to ensure scroll happens first
setTimeout(() => {
runTest(subset, wc, q);
}, 10);
};
// Run capability detection when DOM is fully loaded
document.addEventListener('DOMContentLoaded', () => {
// Re-run capability detection to ensure UI is updated
detectCapabilities();
// Log capabilities to console for debugging
console.log('Browser capabilities detected:', capabilities);
});
// Clean up all resources when page is closed/unloaded
window.addEventListener('unload', () => {
// Clean up the worker blob URL
URL.revokeObjectURL(workerBlobURL);
// Clean up all image blob URLs
cleanupImageBlobURLs();
});
</script>
</body>
</html>