-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path360StickerEdit.html
More file actions
821 lines (713 loc) · 26.5 KB
/
360StickerEdit.html
File metadata and controls
821 lines (713 loc) · 26.5 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>360StickerEdit</title>
<style>
html, body { margin:0; padding:0; overflow:hidden; height:100%; }
#controls { position:absolute; top:0; left:0; width:100%; background:#eee; padding:8px; z-index:10; display:flex; gap:6px; align-items:center; }
button, input { font-size:14px; }
canvas { display:block; }
.selection-box{
position:absolute;
border:2px dashed #0077ff;
pointer-events:none;
transform-origin:center center;
}
.sel-handle{
position:absolute; width:12px; height:12px; background:white; border:1px solid #333; box-sizing:border-box; border-radius:2px;
}
.handle-tl{ top:-6px; left:-6px; cursor:nwse-resize; }
.handle-tr{ top:-6px; right:-6px; cursor:nesw-resize; }
.handle-bl{ bottom:-6px; left:-6px; cursor:nesw-resize; }
.handle-br{ bottom:-6px; right:-6px; cursor:nwse-resize; }
/* Help Dialog Modal */
.modal-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
z-index: 1000;
justify-content: center;
align-items: center;
}
.modal-overlay.active {
display: flex;
}
.modal-dialog {
background: white;
border-radius: 8px;
width: 90%;
max-width: 600px;
max-height: 80vh;
display: flex;
flex-direction: column;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
.modal-header {
padding: 16px 20px;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h2 {
margin: 0;
font-size: 20px;
color: #333;
}
.modal-close {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
color: #666;
padding: 0;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
}
.modal-close:hover {
color: #000;
}
.modal-content {
padding: 20px;
overflow-y: auto;
flex: 1;
}
.modal-content p {
margin: 0 0 16px 0;
line-height: 1.6;
color: #333;
}
.help-bth {
background-color: #e0e0e0;
min-width: 100px;
border-radius: 5px;
border-color: gray;
border-style: outset;
}
.help-keyboard-bth {
display: inline-block;
padding: 2px 5px;
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 4px;
font-family: sans-serif;
font-size: 14px;
color: #333;
box-shadow: 0 4px 0 rgba(0, 0, 0, 0.1), 0 0 0 rgba(0, 0, 0, 0.05);
text-align: center;
}
</style>
</head>
<body>
<div id="controls">
<label>Background (360 equirect): <input type="file" id="bgInput" accept="image/*"></label>
<label>Sticker: <input type="file" id="stickerInput" accept="image/*"></label>
<button id="addSticker">+ Add Sticker</button>
<button id="clearAll">Clear All</button>
<button id="savePng">Save PNG</button>
<button id="saveJpg">Save JPG</button>
<button id="helpBtn">❔Help</button>
</div>
<canvas id="canvas"></canvas>
<div id="selectionBox" class="selection-box" style="display:none">
<div class="sel-handle handle-tl"></div>
<div class="sel-handle handle-tr"></div>
<div class="sel-handle handle-bl"></div>
<div class="sel-handle handle-br"></div>
</div>
<!-- Help Modal Dialog -->
<div id="helpModal" class="modal-overlay">
<div class="modal-dialog">
<div class="modal-header">
<h2>Help - 360StickerEdit</h2>
<button class="modal-close" id="closeHelp">×</button>
</div>
<div class="modal-content">
<h1>INTRO</h1>
<div>
Hello and thank you for using my little tool. It’s nothing to special you can simply put stickers on a 360 image and save them perspectively corrected.
I made (to be fair with the help of AI) this tool because I joined a group of board gamers. We share images on social media. Since we cannot or don’t bother to get the consent of everybody in the boardgame caffe, we cover the faces with the logo of our group, to preserve privacy.
This is easy with 2D images. But I did not find a simple tool for 360 images.
Originally, I used Hugin changed the rotation on a face used a external image editor and I repeated that for every person. This process took ridiculously long.
So here my tool, have fun with 360StickerEdit
</div>
<h1>TOOLBAR BUTTONS</h1>
<ol>
<li>Background (360 equirect): <span class="help-bth">Choose file</span> - Load your 360° equirectangular background image. From your 360 camera or from Hugin.</li>
<li>Sticker: <span class="help-bth">Choose file</span> - Load a sticker/logo image.</li>
<li>Click <span class="help-bth">+ Add Sticker</span> to place it in the scene.</li>
<li><span class="help-bth">Clear All</span> will remove all Stickers. Usefull when you finishe one image and move to the next.</li>
<li><span class="help-bth">Save PNG</span> - Exports as PNG highest quality. However no added metadata (most websites will not recognize it as a 360 image). Only useful if you want to process your image with other image editor, Hugin and add metadata later with for example ExifTool.</li>
<li>Click <span class="help-bth">Save JPG</span> to export with 360° metadata. It exports with max quality settings however JPG is always a lossy format! However it can be directly used on websites</li>
<li><span class="help-bth">❔Help</span> - this help</li>
</ol>
<h1>🖱️ NAVIGATION & CONTROLS</h1>
<p>Organized into sections:</p>
<ul>
<li>Camera Navigation: <span class="help-keyboard-bth">⇧ Shift</span> +drag mouse to rotate</li>
<li>Sticker Selection: Click to select, visual feedback with blue dashed box</li>
<li>
Transform Controls: Detailed <span class="help-keyboard-bth">G</span>/<span class="help-keyboard-bth">S</span>/<span class="help-keyboard-bth">R</span> key explanations<br />
Select a sticker and hold the key on the keyboard for the function.
<ul>
<li><span class="help-keyboard-bth">G</span> (Move): Sticker follows cursor on sphere surface</li>
<li><span class="help-keyboard-bth">S</span> (Scale): Move mouse to/from center to resize</li>
<li><span class="help-keyboard-bth">R</span> (Rotate): Move mouse to rotate</li>
</ul>
</li>
<li><span class="help-keyboard-bth">DEL</span> delete the selected sticker</li>
</ul>
<h1>📝 TYPICAL WORKFLOW</h1>
<ol>
<li>Load background → Load sticker</li>
<li>Navigate with Shift+drag</li>
<li>Add sticker to scene</li>
<li>move/ rotate /scale the sticker to desired postion</li>
<li>repeat</li>
<li>Export as JPG with metadata and share on facebook or google maps</li>
</ol>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.117.1/build/three.min.js"></script>
<script src="OrbitControls.js"></script>
<script>
// ============================================================================
// GLOBAL STATE AND VARIABLES
// ============================================================================
const canvas = document.getElementById('canvas');
const selectionBox = document.getElementById('selectionBox');
// Three.js core objects
let scene, camera, renderer, controls;
let backgroundMesh;
// Sticker management
let stickers = [];
let stickerImage = null;
let selected = null;
// Interaction state
let currentMode = 'selection'; // Modes: 'selection', 'view', 'move', 'scale', 'rotate'
let raycaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();
let lastMouse = {x: 0, y: 0};
let initialDistance = 0;
let initialScale = 1;
let initialRotation = 0;
// Reusable objects to avoid garbage collection during animation
const _axis = new THREE.Vector3();
const _rotQ = new THREE.Quaternion();
const _baseQ = new THREE.Quaternion();
// ============================================================================
// SCENE INITIALIZATION
// ============================================================================
function initScene() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 2000);
camera.position.set(0,0,0.01);
renderer = new THREE.WebGLRenderer({ canvas, preserveDrawingBuffer:true, alpha:true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding;
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableZoom = true;
controls.enablePan = false;
controls.enableRotate = false; // rotate only when control held
const geometry = new THREE.SphereGeometry(500, 64, 64);
geometry.scale(-1,1,1);
const material = new THREE.MeshBasicMaterial({ color:0x999999, depthWrite:true });
backgroundMesh = new THREE.Mesh(geometry, material);
scene.add(backgroundMesh);
window.addEventListener('resize', ()=>{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
}
initScene();
// ============================================================================
// ANIMATION LOOP
// ============================================================================
function animate() {
requestAnimationFrame(animate);
// Update sticker orientations to always face camera with user-applied rotation
stickers.forEach(sticker => {
// Make sticker face the camera
sticker.lookAt(camera.position);
// Calculate axis from sticker to camera
_axis.copy(camera.position).sub(sticker.position).normalize();
// Apply user rotation around the view axis
_rotQ.setFromAxisAngle(_axis, sticker.userData.rotationOffset || 0);
// Combine base orientation with rotation
_baseQ.copy(sticker.quaternion);
sticker.quaternion.copy(_rotQ).multiply(_baseQ);
});
renderer.render(scene, camera);
}
animate();
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
function updateCursor() {
switch(currentMode){
case 'view': canvas.style.cursor='grab'; break;
case 'move': canvas.style.cursor='move'; break;
case 'scale': canvas.style.cursor='nwse-resize'; break;
case 'rotate': canvas.style.cursor='crosshair'; break;
default: canvas.style.cursor='pointer';
}
}
function updateSelectionBox() {
if (!selected) return;
const vector = selected.position.clone().project(camera);
const rect = canvas.getBoundingClientRect();
const x = (vector.x * 0.5 + 0.5) * rect.width;
const y = (-vector.y * 0.5 + 0.5) * rect.height;
selectionBox.style.left = (x - 25) + 'px';
selectionBox.style.top = (y - 25) + 'px';
selectionBox.style.width = '50px';
selectionBox.style.height = '50px';
selectionBox.style.display = 'block';
}
function deselect() {
selected = null;
selectionBox.style.display = 'none';
}
function showHelp() {
const modal = document.getElementById('helpModal');
modal.classList.add('active');
}
function closeHelp() {
const modal = document.getElementById('helpModal');
modal.classList.remove('active');
}
updateCursor();
// ============================================================================
// FILE INPUT HANDLERS AND STICKER CREATION
// ============================================================================
const bgInput = document.getElementById('bgInput');
const stickerInput = document.getElementById('stickerInput');
const addStickerBtn = document.getElementById('addSticker');
// Load 360° background image
bgInput.addEventListener('change', e => {
const file = e.target.files[0];
if(!file) return;
const img = new Image();
img.onload = () => {
const tex = new THREE.Texture(img);
tex.needsUpdate = true;
tex.encoding = THREE.sRGBEncoding;
backgroundMesh.material.map = tex;
backgroundMesh.material.needsUpdate = true;
};
img.src = URL.createObjectURL(file);
});
// Load sticker image
stickerInput.addEventListener('change', e => {
const file = e.target.files[0];
if (!file) return;
const img = new Image();
img.onload = () => { stickerImage = img; };
img.src = URL.createObjectURL(file);
});
// Add sticker to scene
addStickerBtn.addEventListener('click', () => {
if (!stickerImage) return alert('Choose a sticker image');
// Create texture and material
const tex = new THREE.Texture(stickerImage);
tex.needsUpdate = true;
tex.encoding = THREE.sRGBEncoding;
const mat = new THREE.MeshBasicMaterial({
map: tex,
depthTest: false,
transparent: true,
side: THREE.DoubleSide
});
// Calculate dimensions maintaining aspect ratio
const aspect = stickerImage.width / stickerImage.height;
const height = 50;
const width = height * aspect;
// Create plane mesh
const geometry = new THREE.PlaneGeometry(width, height);
const mesh = new THREE.Mesh(geometry, mat);
// Position sticker in front of camera on sphere surface
const vector = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
mesh.position.copy(vector.multiplyScalar(499));
// Store metadata for export
mesh.userData.rotationOffset = 0;
mesh.userData.width = width;
mesh.userData.height = height;
scene.add(mesh);
stickers.push(mesh);
});
// Clear all stickers
const clearAllBtn = document.getElementById('clearAll');
clearAllBtn.addEventListener('click', () => {
if (stickers.length === 0) {
return alert('No stickers to clear');
}
const confirmed = confirm('This will clear all stickers. Are you sure?');
if (confirmed) {
// Remove all stickers from scene
stickers.forEach(sticker => scene.remove(sticker));
// Clear stickers array
stickers = [];
// Deselect if anything was selected
deselect();
}
});
// ============================================================================
// POINTER/MOUSE EVENT HANDLERS
// ============================================================================
// Select/deselect stickers by clicking
canvas.addEventListener('pointerdown', (event) => {
if (!controls.enableRotate) {
const rect = canvas.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(stickers);
if (intersects.length > 0) {
// Toggle selection if clicking same sticker
if (selected != null && selected === intersects[0].object) {
deselect();
} else {
selected = intersects[0].object;
updateSelectionBox();
}
} else {
deselect();
}
}
});
// Track mouse position for move/scale/rotate operations
canvas.addEventListener('pointermove', e => {
lastMouse.x = e.clientX;
lastMouse.y = e.clientY;
if (!selected) return;
const rect = canvas.getBoundingClientRect();
const mousePos = new THREE.Vector2(
((e.clientX - rect.left) / rect.width) * 2 - 1,
-((e.clientY - rect.top) / rect.height) * 2 + 1
);
raycaster.setFromCamera(mousePos, camera);
switch (currentMode) {
case 'move':
const intersects = raycaster.intersectObject(backgroundMesh);
if (intersects.length > 0) {
selected.position.copy(intersects[0].point);
updateSelectionBox();
}
break;
case 'scale':
const scaleIntersects = raycaster.intersectObject(backgroundMesh);
if (scaleIntersects.length > 0) {
const newDist = scaleIntersects[0].point.distanceTo(selected.position);
const scaleFactor = newDist / initialDistance;
selected.scale.set(initialScale * scaleFactor, initialScale * scaleFactor, 1);
updateSelectionBox();
}
break;
case 'rotate': {
// Get screen position of selected sticker
const vector = selected.position.clone().project(camera);
const centerX = (vector.x * 0.5 + 0.5) * rect.width;
const centerY = (-vector.y * 0.5 + 0.5) * rect.height;
// Calculate new distance from center
const dx = e.clientX - centerX;
const dy = e.clientY - centerY;
const newDist = Math.sqrt(dx * dx + dy * dy);
// Convert distance ratio to rotation angle
let ratio = newDist / initialDistance;
let angleDelta = (ratio - 1.0) * Math.PI * 2;
selected.userData.rotationOffset = initialRotation + angleDelta;
updateSelectionBox();
break;
}
}
});
// ============================================================================
// KEYBOARD EVENT HANDLERS
// ============================================================================
window.addEventListener('keydown', e => {
// Shift key enables view mode (orbit controls)
if (e.key === 'Shift') {
currentMode = 'view';
controls.enableRotate = true;
updateCursor();
deselect();
}
if (!selected) return;
// Transform keys only work when in selection mode
if (currentMode === 'selection') {
// G key: Move mode
if (e.key.toLowerCase() === 'g') {
currentMode = 'move';
updateCursor();
}
// S key: Scale mode
if (e.key.toLowerCase() === 's') {
currentMode = 'scale';
const rect = canvas.getBoundingClientRect();
const mousePos = new THREE.Vector2(
((lastMouse.x - rect.left) / rect.width) * 2 - 1,
-((lastMouse.y - rect.top) / rect.height) * 2 + 1
);
// Find initial distance for scaling
raycaster.setFromCamera(mousePos, camera);
const intersects = raycaster.intersectObject(backgroundMesh);
if (intersects.length > 0) {
initialDistance = intersects[0].point.distanceTo(selected.position);
initialScale = selected.scale.x;
}
updateCursor();
}
// R key: Rotate mode
if (e.key.toLowerCase() === 'r') {
currentMode = 'rotate';
initialRotation = selected.userData.rotationOffset || 0;
// Get screen position of sticker
const vector = selected.position.clone().project(camera);
const rect = canvas.getBoundingClientRect();
const centerX = (vector.x * 0.5 + 0.5) * rect.width;
const centerY = (-vector.y * 0.5 + 0.5) * rect.height;
// Calculate initial distance from mouse to sticker center
const dx = lastMouse.x - centerX;
const dy = lastMouse.y - centerY;
initialDistance = Math.sqrt(dx * dx + dy * dy);
updateCursor();
}
// Delete key: Remove sticker
if (e.key === 'Delete' || e.key === 'Del') {
if (selected) {
scene.remove(selected);
const index = stickers.indexOf(selected);
if (index !== -1) stickers.splice(index, 1);
deselect();
}
}
}
});
window.addEventListener('keyup', e => {
// Release Shift to exit view mode
if (e.key === 'Shift') {
currentMode = 'selection';
controls.enableRotate = false;
updateCursor();
}
// Release G/S/R to exit transform modes
if (['g', 's', 'r'].includes(e.key.toLowerCase())) {
currentMode = 'selection';
updateCursor();
}
});
// ============================================================================
// EXPORT FUNCTIONALITY
// ============================================================================
/**
* Creates XMP metadata packet for 360° Photo Sphere
* @param {number} width - Image width in pixels
* @param {number} height - Image height in pixels
* @returns {string} Complete XMP packet as XML string
*/
function createPhotoSphereXMP(width, height) {
const xmpTemplate = `<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.0-jc003">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""
xmlns:GPano="http://ns.google.com/photos/1.0/panorama/"
GPano:ProjectionType="equirectangular"
GPano:UsePanoramaViewer="True"
GPano:CroppedAreaImageWidthPixels="${width}"
GPano:CroppedAreaImageHeightPixels="${height}"
GPano:FullPanoWidthPixels="${width}"
GPano:FullPanoHeightPixels="${height}"
GPano:CroppedAreaLeftPixels="0"
GPano:CroppedAreaTopPixels="0"
GPano:PoseHeadingDegrees="0.0"/>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>`;
return xmpTemplate;
}
/**
* Injects XMP metadata into JPEG ArrayBuffer
* @param {ArrayBuffer} jpegBuffer - Original JPEG data
* @param {string} xmpData - XMP packet to inject
* @returns {ArrayBuffer} New JPEG with XMP metadata
*/
function injectXMPIntoJPEG(jpegBuffer, xmpData) {
const jpegView = new Uint8Array(jpegBuffer);
// JPEG starts with SOI marker: 0xFF 0xD8
if (jpegView[0] !== 0xFF || jpegView[1] !== 0xD8) {
throw new Error('Not a valid JPEG file');
}
// XMP APP1 segment structure:
// 0xFF 0xE1 (APP1 marker)
// 2 bytes: segment length (big-endian, includes length bytes but not marker)
// "http://ns.adobe.com/xap/1.0/\0" (29 bytes - XMP identifier)
// XMP data
const xmpIdentifier = 'http://ns.adobe.com/xap/1.0/\0';
const xmpBytes = new TextEncoder().encode(xmpData);
const identifierBytes = new TextEncoder().encode(xmpIdentifier);
// Calculate segment length: length field (2) + identifier (29) + xmp data
const segmentLength = 2 + identifierBytes.length + xmpBytes.length;
// Create APP1 segment
const app1Segment = new Uint8Array(2 + segmentLength);
let offset = 0;
// APP1 marker
app1Segment[offset++] = 0xFF;
app1Segment[offset++] = 0xE1;
// Segment length (big-endian)
app1Segment[offset++] = (segmentLength >> 8) & 0xFF;
app1Segment[offset++] = segmentLength & 0xFF;
// XMP identifier
app1Segment.set(identifierBytes, offset);
offset += identifierBytes.length;
// XMP data
app1Segment.set(xmpBytes, offset);
// Find where to insert: after SOI (0xFF 0xD8) and APP0 if present
let insertPosition = 2; // After SOI
// Check if APP0 exists (0xFF 0xE0)
if (jpegView[2] === 0xFF && jpegView[3] === 0xE0) {
// Skip APP0 segment: marker (2) + length field (2) + data
const app0Length = (jpegView[4] << 8) | jpegView[5];
insertPosition = 4 + app0Length; // After APP0
}
// Construct new JPEG: [start] + [XMP APP1] + [rest]
const newJpeg = new Uint8Array(insertPosition + app1Segment.length + (jpegView.length - insertPosition));
newJpeg.set(jpegView.slice(0, insertPosition), 0);
newJpeg.set(app1Segment, insertPosition);
newJpeg.set(jpegView.slice(insertPosition), insertPosition + app1Segment.length);
return newJpeg.buffer;
}
/**
* Export the composed 360° image as PNG or JPEG
* Process: Render scene to cube map -> Convert cube map to equirectangular -> Download
*/
function saveEquirectThree(format = 'png') {
if (!backgroundMesh.material.map) {
return alert('Load a background first');
}
const width = backgroundMesh.material.map.image.width;
const height = backgroundMesh.material.map.image.height;
// Step 1: Render the scene to a cube map from the origin
const cubeRenderTarget = new THREE.WebGLCubeRenderTarget(width, {
format: THREE.RGBAFormat,
type: THREE.UnsignedByteType,
generateMipmaps: false,
encoding: THREE.sRGBEncoding
});
const cubeCamera = new THREE.CubeCamera(0.1, 2000, cubeRenderTarget);
cubeCamera.update(renderer, scene);
// Step 2: Convert cube map to equirectangular projection
const equirectRenderTarget = new THREE.WebGLRenderTarget(width, height, {
format: THREE.RGBAFormat,
type: THREE.UnsignedByteType,
encoding: THREE.sRGBEncoding
});
// Shader converts each equirect UV coordinate to a 3D direction vector
// and samples the cube map in that direction
const material = new THREE.ShaderMaterial({
uniforms: { tCube: { value: cubeRenderTarget.texture } },
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position, 1.0);
}
`,
fragmentShader: `
#include <common>
uniform samplerCube tCube;
varying vec2 vUv;
void main() {
vec2 uv = vUv;
float theta = PI - uv.x * 2.0 * PI;
float phi = uv.y * PI;
vec3 dir = vec3(
sin(phi) * sin(theta),
cos(phi),
sin(phi) * cos(theta)
);
gl_FragColor = textureCube(tCube, dir);
}
`,
side: THREE.DoubleSide
});
// Render a fullscreen quad with the conversion shader
const quadScene = new THREE.Scene();
const quadCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
const quad = new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), material);
quadScene.add(quad);
renderer.setRenderTarget(equirectRenderTarget);
renderer.render(quadScene, quadCamera);
renderer.setRenderTarget(null);
// Step 3: Copy pixels from WebGL render target to canvas for export
const buffer = new Uint8Array(4 * width * height);
renderer.readRenderTargetPixels(equirectRenderTarget, 0, 0, width, height, buffer);
const canvas2 = document.createElement('canvas');
canvas2.width = width;
canvas2.height = height;
const ctx = canvas2.getContext('2d');
const imageData = ctx.createImageData(width, height);
for (let i = 0; i < buffer.length; i++) {
imageData.data[i] = buffer[i];
}
ctx.putImageData(imageData, 0, 0);
// Step 4: Convert to blob and inject metadata for JPEG
if (format === 'jpeg') {
// Convert canvas to blob with maximum quality
canvas2.toBlob(async (blob) => {
// Read blob as ArrayBuffer
const arrayBuffer = await blob.arrayBuffer();
// Create and inject XMP metadata
const xmpData = createPhotoSphereXMP(width, height);
const modifiedJpeg = injectXMPIntoJPEG(arrayBuffer, xmpData);
// Create blob from modified JPEG
const finalBlob = new Blob([modifiedJpeg], { type: 'image/jpeg' });
// Download
const link = document.createElement('a');
link.download = 'composition.jpg';
link.href = URL.createObjectURL(finalBlob);
link.click();
// Clean up
setTimeout(() => URL.revokeObjectURL(link.href), 100);
}, 'image/jpeg', 1.0); // Maximum quality
} else {
// PNG export (no metadata needed)
const link = document.createElement('a');
link.download = 'composition.png';
link.href = canvas2.toDataURL('image/png');
link.click();
}
}
// Attach export button handlers
document.getElementById('savePng').addEventListener('click', () => {
const confirmed = confirm(
'PNG images don\'t have 360 metadata. Most websites will not recognize it as a 360 image!\n\n' +
'However, you may want to use this export function if you want to process the image further in other software.\n\n' +
'Continue with PNG export?'
);
if (confirmed) {
saveEquirectThree('png');
}
});
document.getElementById('saveJpg').addEventListener('click', () => saveEquirectThree('jpeg'));
// Attach help button handlers
document.getElementById('helpBtn').addEventListener('click', showHelp);
document.getElementById('closeHelp').addEventListener('click', closeHelp);
// Close modal when clicking on overlay (outside the dialog)
document.getElementById('helpModal').addEventListener('click', (e) => {
if (e.target.id === 'helpModal') {
closeHelp();
}
});
</script>
</body>
</html>