-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
2188 lines (1865 loc) · 103 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
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"> <!-- Added language declaration -->
<head>
<title>Interactive Astigmatism Wheel: Explore & Visualize Online</title> <!-- Slightly more active title -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Added viewport for mobile -->
<!-- Basic Metadata -->
<meta name="author" content="Frincu Madalin">
<meta name="copyright" content="© 2024 Frincu Madalin. All Rights Reserved.">
<meta name="license" content="http://creativecommons.org/licenses/by-nc-sa/4.0/">
<meta name="google-site-verification" content="Nq5VPR_L9XqPIXpH4yenmGVKwdxyMAerw6HSiSwSDcA" />
<!-- SEO Meta Tags - Enhanced -->
<meta name="description"
content="Explore astigmatism with this interactive online wheel visualization. Adjust line count, colors, rotation, anaglyph 3D, and autopilot modes. A web-based tool for learning and visual exploration, not a medical diagnosis."> <!-- Refined description -->
<meta name="keywords"
content="astigmatism, astigmatism wheel, interactive visualization, eye chart simulation, ophthalmology tool, vision visualization, visual acuity, refractive error, anaglyph 3D vision, interactive eye simulation, web-based vision tool, online astigmatism explorer, learn about astigmatism, javascript canvas animation"> <!-- Expanded keywords -->
<link rel="canonical" href="https://madalin-fr.github.io/AstigmatismWheelInteraction/">
<meta name="robots" content="index, follow">
<!-- Open Graph / Social Media Meta Tags -->
<meta property="og:title" content="Interactive Astigmatism Wheel Visualization">
<meta property="og:description"
content="Explore astigmatism visually with adjustable settings like anaglyph 3D, line count, colors, and autopilot modes. An interactive learning tool."> <!-- Slightly refined OG desc -->
<meta property="og:image" content="https://madalin-fr.github.io/AstigmatismWheelInteraction/assets/preview-image-3.png">
<meta property="og:url" content="https://madalin-fr.github.io/AstigmatismWheelInteraction/">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Astigmatism Wheel Interactions"> <!-- Added Site Name -->
<meta property="og:locale" content="en_US"> <!-- Added Locale -->
<!-- Twitter Card Meta Tags -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Interactive Astigmatism Wheel Visualization">
<meta name="twitter:description" content="An interactive online tool to visualize and explore the concepts of astigmatism with various customizable settings."> <!-- Slightly refined Twitter desc -->
<meta name="twitter:image" content="https://madalin-fr.github.io/AstigmatismWheelInteraction/assets/preview-image-3.png">
<!-- <meta name="twitter:site" content="@yourtwitterhandle"> --> <!-- Optional: Add if you have a related Twitter account -->
<!-- <meta name="twitter:creator" content="@yourtwitterhandle"> --> <!-- Optional: Add if you have a related Twitter account -->
<!-- Removed the second, redundant meta description tag -->
<style>
/* Visually hide h1, but keep for SEO/Screen Readers */
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: #000000; /* Default BG set via JS, but good to have a fallback */
}
/* (Rest of your existing CSS remains unchanged) */
div#title { /* Note: This div isn't present in the body, consider removing if unused */
position: absolute;
top: 1rem;
left: 2rem;
text-align: left;
}
canvas {
position: absolute;
margin: auto;
/* Accessibility Note: Canvas content is not directly accessible.
Ensure descriptions and controls provide context. */
}
div#info { /* Note: This div isn't present in the body, consider removing if unused */
position: absolute;
bottom: 1rem;
left: 1rem;
font-size: 1.5rem;
}
p#license { /* Note: This p isn't present in the body, consider removing if unused */
position: absolute;
bottom: 1rem;
right: 1rem;
line-height: 2rem;
}
#controls-container {
position: absolute;
top: 1rem;
left: 1rem;
z-index: 10;
}
#drag-handle {
background-color: rgba(255, 255, 255, 0.8);
padding: 8px;
border-radius: 4px;
border: 1px solid #666;
transition: all 0.3s ease;
}
#drag-handle.dark-mode {
background-color: rgba(30, 30, 30, 0.9);
border-color: #999;
}
#controls-container {
display: flex;
align-items: center;
gap: 10px;
}
#controls-container.reverse {
flex-direction: row-reverse;
}
#flip-position {
background: none;
border: none;
font-size: 1.4rem;
cursor: pointer;
padding: 0;
color: #333;
transition: color 0.3s ease;
}
#flip-position.dark-mode {
color: white;
}
#toggle-menu {
padding: 1px 25px;
border-radius: 4px;
cursor: pointer;
border: 1px solid #666;
background-color: rgba(255, 255, 255, 0.8);
color: black;
transition: all 0.3s ease;
}
#toggle-menu.dark-mode {
background-color: rgba(30, 30, 30, 0.9);
color: white;
border-color: #999;
}
#drag-handle i {
transition: color 0.3s ease;
}
#drag-handle.dark-mode i {
color: white;
}
#controls {
display: none;
position: absolute;
top: 35px;
left: 0;
background-color: rgba(255, 255, 255, 0.8);
padding: 1rem;
border-radius: 8px;
max-height: calc(100vh - 4rem);
overflow-y: auto;
width: 200px;
opacity: 1;
transition: background-color 0.3s ease, opacity 0.3s ease;
color: black;
}
#toggle-autopilot-1,
#toggle-autopilot-2 {
padding: 2px 16px;
border-radius: 4px;
cursor: pointer;
border: 1px solid #666;
background-color: rgba(255, 255, 255, 0.8);
color: black;
transition: all 0.3s ease;
margin-bottom: 5px;
}
#toggle-autopilot-1.dark-mode,
#toggle-autopilot-2.dark-mode {
background-color: rgba(30, 30, 30, 0.9);
color: white;
border-color: #999;
}
#controls.dark-mode {
background-color: rgba(30, 30, 30, 0.9);
color: white;
}
#controls.dark-mode input[type='color'] {
background-color: white; /* Consider styling these better for dark mode if needed */
}
#controls.dark-mode input[type='range'] {
/* Consider styling these better for dark mode if needed */
}
#controls h3 {
margin-right: 10px;
margin-top: 0; /* Good practice to reset margin */
}
#controls #toggle-dark-mode {
background: none;
border: none;
font-size: 1.4rem;
padding: 0px;
cursor: pointer;
margin: 0px;
position: relative; /* Or adjust layout as needed */
}
#controls #toggle-dark-mode i {
color: #333;
transition: all 0.3s ease-in-out;
}
#controls #toggle-dark-mode i.fa-sun {
color: #FFD700;
text-shadow: 0 0 2px #fff;
}
#controls.dark-mode #toggle-dark-mode i.fa-moon {
color: #FFFF80; /* Adjusted moon color for visibility */
}
#controls.dark-mode #toggle-dark-mode i.fa-sun {
/* Sun icon when dark mode is active - keep it distinct */
color: #A9A9A9; /* Example: Dim yellow/grey */
}
#controls #opacity-slider {
width: calc(100% - 2rem); /* Check layout, ensure label fits */
}
#zoom-controls {
position: absolute;
top: 1rem;
right: 1rem;
z-index: 10;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
#zoom-controls button {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid #666;
border-radius: 4px;
padding: 8px;
cursor: pointer;
font-size: 1rem;
color: black;
transition: all 0.3s ease;
width: 35px; /* Ensure consistent button size */
height: 35px;
display: flex; /* Center content */
align-items: center;
justify-content: center;
}
#zoom-controls button.dark-mode {
background-color: rgba(30, 30, 30, 0.8);
color: white;
border-color: #999;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<!-- Structured Data (Schema.org - JSON-LD) -->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "WebPage",
"name": "Interactive Astigmatism Wheel: Explore & Visualize Online",
"description": "Explore astigmatism with this interactive online wheel visualization. Adjust line count, colors, rotation, anaglyph 3D, and autopilot modes. A web-based tool for learning and visual exploration, not a medical diagnosis.",
"url": "https://madalin-fr.github.io/AstigmatismWheelInteraction/",
"author": {
"@type": "Person",
"name": "Frincu Madalin"
},
"license": "http://creativecommons.org/licenses/by-nc-sa/4.0/",
"keywords": "astigmatism, astigmatism wheel, interactive visualization, eye chart simulation, ophthalmology tool, vision visualization, visual acuity, refractive error, anaglyph 3D vision, interactive eye simulation, web-based vision tool, online astigmatism explorer, learn about astigmatism",
"mainEntity": {
"@type": "WebApplication",
"name": "Astigmatism Wheel Interactions",
"description": "An interactive web application for visualizing astigmatism concepts using a rotating wheel chart with customizable parameters.",
"applicationCategory": "VisualizationTool",
"operatingSystem": "Web/Online",
"browserRequirements": "Requires JavaScript and HTML5 Canvas support.",
"author": {
"@type": "Person",
"name": "Frincu Madalin"
},
"copyrightHolder": {
"@type": "Person",
"name": "Frincu Madalin"
},
"license": "http://creativecommons.org/licenses/by-nc-sa/4.0/",
"url": "https://madalin-fr.github.io/AstigmatismWheelInteraction/",
"image": "https://madalin-fr.github.io/AstigmatismWheelInteraction/assets/preview-image-3.png",
"featureList": [
"Multiple visualization modes (Many Lines, Single Line, Pendulum, Anaglyph 3D)",
"Adjustable line count, color, thickness, length",
"Customizable background and text colors",
"Anaglyph 3D mode with adjustable depth and eye colors",
"Interactive rotation control",
"Autopilot modes for automatic animation",
"Zoom and Pan functionality",
"Dark/Light mode toggle",
"Draggable controls interface"
]
}
}
</script>
</head>
<body>
<!-- Visually Hidden H1 for SEO -->
<h1 class="visually-hidden">Interactive Astigmatism Wheel: Explore & Visualize Online</h1>
<!-- Main Content Area -->
<main>
<canvas id="canvas" width="6400" height="3153">
<!-- Fallback content for non-supporting browsers -->
Your browser does not support the HTML5 canvas element. This interactive visualization requires a modern browser with Canvas support.
</canvas>
<!-- Controls container -->
<div id="controls-container" class="draggable">
<div id="drag-handle" title="Drag Controls"> <!-- Added title for usability -->
<i class="fas fa-arrows-alt"></i>
</div>
<button id="toggle-menu" title="Show/Hide Controls Menu">Show Controls</button> <!-- Added title -->
<div id="controls">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 10px;"> <!-- Added margin -->
<h3>Adjust Settings</h3>
<button id="toggle-dark-mode" title="Toggle Dark/Light Mode"> <!-- Added title -->
<i class="fas fa-sun"></i> <!-- Icon changes via JS -->
</button>
<button id="flip-position" title="Flip Controls Position"> <!-- Added title -->
<i class="fas fa-exchange-alt"></i>
</button>
</div>
<label for="visualization-mode">Mode:</label>
<select id="visualization-mode" style="width: 100%; margin-bottom: 10px;">
<option value="many">Many Lines</option>
<option value="single">Single Line</option>
<option value="pendulum">Pendulum</option>
<option value="anaglyph">Anaglyph 3D</option>
</select>
<br>
<label for="opacity-slider">Controls Opacity:</label> <!-- Clarified label -->
<input type="range" id="opacity-slider" min="0.1" max="1.0" step="0.1" value="1.0">
<br>
<div id="radiating-line-count-container">
<label for="radiating-line-count">Radiating Line Count:</label>
<input type="range" id="radiating-line-count" min="2" max="72" value="3">
</div>
<div id="line-color-container">
<label for="line-color">Line Color:</label>
<input type="color" id="line-color" value="#7B68EE">
</div>
<!-- Label text updated dynamically via JS -->
<label for="special-line-color" id="special-line-color-label">Special Line Color:</label>
<input type="color" id="special-line-color" value="#FFFFFF">
<br>
<!--Anaglyph Color Pickers-->
<div id="anaglyph-color-pickers" style="display: none;">
<label for="anaglyph-left-color">Left Eye Color:</label>
<input type="color" id="anaglyph-left-color" value="#ff0000">
<br>
<label for="anaglyph-right-color">Right Eye Color:</label>
<input type="color" id="anaglyph-right-color" value="#00ffff">
<br>
</div>
<label for="bg-color">Background Color:</label>
<input type="color" id="bg-color" value="#ff0000"> <!-- Initial value overridden by JS/LocalStorage -->
<br>
<label for="text-color">Text Color:</label>
<input type="color" id="text-color" value="#800080"> <!-- Initial value overridden by JS/LocalStorage -->
<br>
<label for="circle-outline-color">Circle Outline Color:</label> <!-- Corrected label text -->
<input type="color" id="circle-outline-color" value="#ffffff"> <!-- Initial value overridden by JS/LocalStorage -->
<br>
<label for="horizontal-offset">Horizontal Offset:</label>
<input type="range" id="horizontal-offset" min="-1200" max="1200" value="0">
<br>
<label for="vertical-offset">Vertical Offset:</label>
<input type="range" id="vertical-offset" min="-1200" max="1200" value="0">
<br>
<label for="arc-offset">Circle Radius Offset:</label> <!-- Clarified label -->
<input type="range" id="arc-offset" min="-200" max="1200" value="0">
<br>
<label for="circle-outline-dash-density">Arc Dash Density:</label>
<input type="range" id="circle-outline-dash-density" min="1" max="48" value="15">
<br>
<label for="text-size">Text Size (px):</label> <!-- Added unit -->
<input type="range" id="text-size" min="8" max="72" value="12">
<br>
<label for="text-distance">Text Distance (Factor):</label> <!-- Clarified label -->
<input type="range" id="text-distance" min="1.0" max="5.0" step="0.1" value="1.5">
<br>
<div id="pendulum-size-container" style="display: none;">
<label for="pendulum-thickness">Pendulum Thickness:</label>
<input type="range" id="pendulum-thickness" min="1" max="500" value="20">
</div>
<!-- Depth offset for anaglyph -->
<div id="depth-offset-container" style="display: none;">
<label for="depth-offset">Anaglyph Depth Offset:</label> <!-- Clarified label -->
<input type="range" id="depth-offset" min="1" max="100" value="10">
<br>
</div>
<label for="line-thickness">Line Thickness:</label>
<input type="range" id="line-thickness" min="1" max="40" value="4">
<br>
<label for="line-length">Line Length (Factor):</label> <!-- Clarified label -->
<input type="range" id="line-length" min="0.1" max="4.0" step="0.1" value="1.0">
<br>
<label for="rotation-velocity">Rotation Velocity:</label>
<input type="range" id="rotation-velocity" min="0.1" max="10" step="0.1" value="1">
<br>
<label for="autopilot-speed">Autopilot Speed:</label>
<input type="range" id="autopilot-speed" min="5" max="40" value="10">
<br>
<!-- New Autopilot Walk Range Control -->
<label for="autopilot-walk-range">Autopilot Walk Range (%):</label>
<input type="range" id="autopilot-walk-range" min="0" max="90" value="30">
<br>
<!-- Autopilot Toggles -->
<div style="margin-bottom: 10px;">
<button id="toggle-autopilot-1" title="Start/Stop Autopilot Mode 1 (Smooth Rotation, Random Jumps)">Start Autopilot 1</button> <!-- Added title -->
</div>
<div>
<button id="toggle-autopilot-2" title="Start/Stop Autopilot Mode 2 (Smooth Rotation, Smooth Transitions)">Start Autopilot 2</button> <!-- Added title -->
</div>
<!-- Rotation Direction Checkboxes -->
<div style="margin-top: 10px;"> <!-- Added spacing -->
<input type="checkbox" id="rotate-clockwise" checked>
<label for="rotate-clockwise">Rotate Clockwise</label> <br>
<input type="checkbox" id="rotate-counterclockwise">
<label for="rotate-counterclockwise">Rotate Counter-Clockwise</label>
</div>
</div>
</div>
<!-- Zoom controls -->
<div id="zoom-controls">
<button id="zoom-in" title="Zoom In">+</button> <!-- Added title -->
<button id="zoom-out" title="Zoom Out">-</button> <!-- Added title -->
</div>
</main> <!-- End Main Content Area -->
<!-- Footer or other semantic regions could go here if needed -->
<script>
// --- Utility Functions ---
function standardize_color(str) {
// Check if the input is already a valid hex6 color
if (/^#[0-9A-F]{6}$/i.test(str)) {
return str.toLowerCase(); // Return as is if valid hex6
}
// Otherwise, use canvas to parse and standardize
var ctx = document.createElement('canvas').getContext('2d');
ctx.fillStyle = str; // This forces the browser to parse the color.
let standardized = ctx.fillStyle;
// Ensure it's always lowercase hex6 if possible
if (standardized.startsWith('#') && standardized.length === 7) {
return standardized.toLowerCase();
}
// Fallback if standardization produces something else (e.g., rgba) - though hex is preferred
return standardized;
}
function setBackgroundColor(color) {
document.body.style.backgroundColor = color;
}
// --- Local Storage Functions ---
function getLocalStorageValue(k) {
try {
const value = localStorage.getItem(k);
// console.log(`LS GET: ${k} = ${value}`); // Debug LS
return value;
} catch (error) {
console.error("Error reading from localStorage:", error); // Add error logging
return null;
}
}
function setLocalStorageValue(k, v) {
try {
// console.log(`LS SET: ${k} = ${v}`); // Debug LS
localStorage.setItem(k, v);
} catch (error) {
console.error("Error writing to localStorage:", error); // Add error logging
// Potentially handle quota exceeded error
}
}
function initializeLocalStorage(key, defaultValue) {
if (getLocalStorageValue(key) === null) {
// console.log(`LS INIT: ${key} with default ${defaultValue}`); // Debug LS
setLocalStorageValue(key, defaultValue);
}
}
function angleName(num) {
// Ensure angle is within 0-360 range
num = ((num % 360) + 360) % 360;
// Precision adjustment: Use Math.round for cleaner degrees
if (num >= 90 && num <= 270) { // Handles 90 and 270 inclusive
return Math.round(num - 90) + "°";
} else if (num > 270 && num < 360) { // Handles > 270
return Math.round(num - 270) + "°";
} else { // Handles 0 to < 90 (including 0) and 360 wraps to 0
return Math.round(num + 90) + "°";
}
}
// --- Initialization and Setup ---
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d", { alpha: false }); // optimize if no transparency needed behind canvas
context.imageSmoothingEnabled = true; // Enable anti-aliasing by default
// Initialize canvas dimensions.
let canvasHeight = window.innerHeight;
let canvasWidth = window.innerWidth;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// Make radius slightly smaller to give more padding by default
let radius = Math.min(canvasWidth, canvasHeight) / 4.5;
// --- Zoom functionality ---
let scale = 1;
const minScale = 0.1; // Minimum zoom out
const maxScale = 10.0; // Maximum zoom in
let zoomFactor = 1.1;
let originX = canvasWidth / 2; // Start zoomed to center
let originY = canvasHeight / 2;
let isDragging = false;
let lastX = 0;
let lastY = 0;
// --- Panning state (relative to the *view*) ---
let viewOriginX = 0;
let viewOriginY = 0;
function initializeZoomAndPan() {
const zoomInButton = document.getElementById('zoom-in');
const zoomOutButton = document.getElementById('zoom-out');
zoomInButton.addEventListener('click', () => zoom(1 / zoomFactor, canvasWidth / 2, canvasHeight / 2));
zoomOutButton.addEventListener('click', () => zoom(zoomFactor, canvasWidth / 2, canvasHeight / 2));
canvas.addEventListener('wheel', function (event) {
event.preventDefault(); // Prevent page scrolling
const delta = event.deltaY > 0 ? zoomFactor : 1 / zoomFactor;
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
zoom(delta, mouseX, mouseY);
});
// --- Touch Events for Mobile Pan and Pinch Zoom ---
let pinchStartDistance = 0;
let touchStartX = 0;
let touchStartY = 0;
canvas.addEventListener('touchstart', (event) => {
if (event.touches.length === 1) {
// Start panning
isDragging = true;
const touch = event.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
// Store initial view origin for relative panning
lastX = viewOriginX;
lastY = viewOriginY;
} else if (event.touches.length === 2) {
// Start pinching
isDragging = false; // Stop panning if pinching starts
event.preventDefault(); // Prevent default pinch actions
const touch1 = event.touches[0];
const touch2 = event.touches[1];
pinchStartDistance = Math.hypot(touch1.clientX - touch2.clientX, touch1.clientY - touch2.clientY);
}
});
canvas.addEventListener('touchmove', (event) => {
event.preventDefault(); // Prevent scrolling during touch move
if (event.touches.length === 1 && isDragging) {
// Panning
const touch = event.touches[0];
const dx = touch.clientX - touchStartX;
const dy = touch.clientY - touchStartY;
// Update view origin based on drag from initial touch start position
viewOriginX = lastX + dx;
viewOriginY = lastY + dy;
updateCanvasTransform();
} else if (event.touches.length === 2) {
// Pinching
const touch1 = event.touches[0];
const touch2 = event.touches[1];
const currentDistance = Math.hypot(touch1.clientX - touch2.clientX, touch1.clientY - touch2.clientY);
const delta = pinchStartDistance / currentDistance; // Inverse relationship: smaller distance -> zoom in
// Calculate pinch center
const rect = canvas.getBoundingClientRect();
const pinchCenterX = ((touch1.clientX + touch2.clientX) / 2) - rect.left;
const pinchCenterY = ((touch1.clientY + touch2.clientY) / 2) - rect.top;
zoom(delta, pinchCenterX, pinchCenterY);
pinchStartDistance = currentDistance; // Update start distance for continuous zoom
}
});
canvas.addEventListener('touchend', (event) => {
if (event.touches.length < 2) {
pinchStartDistance = 0; // Reset pinch distance
}
if (event.touches.length < 1) {
isDragging = false; // Stop dragging when no fingers are down
}
});
canvas.addEventListener('touchcancel', (event) => {
isDragging = false;
pinchStartDistance = 0;
});
// Mouse drag panning
canvas.addEventListener('mousedown', function (event) {
if (event.button !== 0) return; // Only pan with left mouse button
isDragging = true;
touchStartX = event.clientX; // Use same vars for consistency
touchStartY = event.clientY;
lastX = viewOriginX; // Store initial view origin
lastY = viewOriginY;
canvas.style.cursor = 'grabbing'; // Indicate panning
});
canvas.addEventListener('mousemove', function (event) {
if (isDragging) {
const dx = event.clientX - touchStartX;
const dy = event.clientY - touchStartY;
viewOriginX = lastX + dx; // Update relative to initial position
viewOriginY = lastY + dy;
updateCanvasTransform();
}
});
canvas.addEventListener('mouseup', function (event) {
if (event.button === 0) {
isDragging = false;
canvas.style.cursor = 'grab'; // Reset cursor
}
});
canvas.addEventListener('mouseleave', function (event) {
if (isDragging) { // Only stop dragging if it was initiated on the canvas
isDragging = false;
canvas.style.cursor = 'default'; // Or 'grab' if preferred
}
});
// Set initial cursor state
canvas.style.cursor = 'grab';
}
function zoom(delta, pointX, pointY) {
const newScale = Math.max(minScale, Math.min(scale * delta, maxScale));
const scaleChange = newScale / scale; // Ratio of new scale to old scale
// Adjust view origin based on the zoom point
// The point (pointX, pointY) in the *view* should remain at the same *relative* position
// after zooming.
viewOriginX = pointX - (pointX - viewOriginX) * scaleChange;
viewOriginY = pointY - (pointY - viewOriginY) * scaleChange;
scale = newScale;
updateCanvasTransform();
}
function updateCanvasTransform() {
// Apply the transformations: first scale, then translate
// This means scaling happens around the (0,0) point of the *canvas*,
// and then the viewOrigin translation moves the desired point to the top-left.
context.setTransform(scale, 0, 0, scale, viewOriginX, viewOriginY);
// Request redraw
if(!shouldAnimate) { // Only redraw immediately if not animating
requestAnimationFrame(draw); // Use rAF for smoother redraws
}
// No explicit draw() call here - it will be handled by the animation loop or the rAF above
}
// --- END ZOOM/PAN FUNCTIONALITY ---
// Default settings object - Stricter defaults for colors
const defaultSettings = {
mode: 'many',
color_many: '#7b68ee', // mediumslateblue
color2_many: '#ffffff', // white
color_single: '#ffffff', // white (as it's the only line)
color2_single: '#ffffff', // white (used for the single line) - consistent
color_pendulum: '#ffd700', // gold
color2_pendulum: '#c0c0c0', // silver
color3: '#ffffff', // white (circle outline) - Consistent Key Name!
anaglyphLeftColor: '#ff0000', // red
anaglyphRightColor: '#00ffff', // cyan
bgColor_many: '#000000', // black
bgColor_single: '#000000', // black
bgColor_pendulum: '#2f4f4f', // darkslategray
bgColor_anaglyph: '#000000', // black (often better contrast for anaglyph)
textColor_many: '#ffffff', // white (better default on black bg)
textColor_single: '#ffffff', // white (better default on black bg)
textColor_pendulum: '#ffffff', // white
textColor_anaglyph: '#ffffff', // white (will be drawn twice in eye colors)
textSize: '14', // Slightly larger default
pendulumThickness: '20',
textDistance: '1.6', // Slightly further default
startAngle: '0',
horizontalOffset: '0',
verticalOffset: '0',
arcOffset: '0',
rotationVelocity: '1.0',
lineLength: '1.0',
isDarkMode: 'true', // Default to dark mode? Or false? Let's try true.
isReversed: 'false',
lineThickness: '4',
radiatingLineCount: '12', // More common default (like a clock)
autopilotSpeed: '10',
rotateClockwise: 'true',
rotateCounterclockwise: 'false',
opacity: '0.9', // Slightly transparent controls default
autopilotWalkRange: '30',
controlsPosition: JSON.stringify({ x: 16, y: 16 }), // Default top-left
circleOutlineDashDensity: '15', // Adjusted default
depthOffset: '5', // Smaller default depth
};
// Initialize LS *before* retrieving values
for (const key in defaultSettings) {
initializeLocalStorage(key, defaultSettings[key]);
}
// Retrieve values from localStorage *after* initializing defaults.
let mode = getLocalStorageValue('mode');
// Use helper function to get mode-specific colors/settings
function getModeSetting(baseKey, currentMode) {
const modeSpecificKey = `${baseKey}_${currentMode}`;
const value = getLocalStorageValue(modeSpecificKey);
// console.log(`Getting setting: ${modeSpecificKey}, Value: ${value}`); // Debug
if (value !== null) {
return value;
}
// Fallback to default for that mode if LS key exists
if (defaultSettings[modeSpecificKey] !== undefined) {
// console.log(`Falling back to default for mode: ${modeSpecificKey}`); // Debug
return defaultSettings[modeSpecificKey];
}
// Absolute fallback to the base default (e.g., if a mode was added later)
// console.log(`Falling back to absolute default: ${baseKey}`); // Debug
return defaultSettings[baseKey] || null; // Or handle error
}
// Standardize colors retrieved from LS or defaults
let color = standardize_color(getModeSetting('color', mode));
let color2 = standardize_color(getModeSetting('color2', mode));
let color3 = standardize_color(getLocalStorageValue('color3')); // Circle Outline (common)
let bgColor = standardize_color(getModeSetting('bgColor', mode));
let textColor = standardize_color(getModeSetting('textColor', mode));
let anaglyphLeftColor = standardize_color(getLocalStorageValue('anaglyphLeftColor'));
let anaglyphRightColor = standardize_color(getLocalStorageValue('anaglyphRightColor'));
// Numeric and boolean settings
let textSize = parseInt(getLocalStorageValue('textSize'));
let pendulumThickness = parseInt(getLocalStorageValue('pendulumThickness'));
let textDistance = parseFloat(getLocalStorageValue('textDistance'));
let horizontalOffset = parseInt(getLocalStorageValue('horizontalOffset')); // World offset
let verticalOffset = parseInt(getLocalStorageValue('verticalOffset')); // World offset
let arcOffset = parseInt(getLocalStorageValue('arcOffset'));
let rotationVelocity = parseFloat(getLocalStorageValue('rotationVelocity'));
let lineLength = parseFloat(getLocalStorageValue('lineLength'));
let isDarkMode = getLocalStorageValue('isDarkMode') === 'true';
let isReversed = getLocalStorageValue('isReversed') === 'true';
let lineThickness = parseInt(getLocalStorageValue('lineThickness'));
let radiatingLineCount = parseInt(getLocalStorageValue('radiatingLineCount'));
let startAngle = parseFloat(getLocalStorageValue('startAngle')); // Use float for smoother animation
let autopilotSpeed = parseInt(getLocalStorageValue('autopilotSpeed'));
let rotateClockwise = getLocalStorageValue('rotateClockwise') === 'true';
let rotateCounterclockwise = getLocalStorageValue('rotateCounterclockwise') === 'false'; // Ensure only one is true initially
let opacity = parseFloat(getLocalStorageValue('opacity'));
let autopilotWalkRange = parseInt(getLocalStorageValue('autopilotWalkRange'));
let circleOutlineDashDensity = parseInt(getLocalStorageValue('circleOutlineDashDensity'));
let depthOffset = parseInt(getLocalStorageValue('depthOffset'));
// Initialize pendulum variables
let pendulumAngle = parseFloat(getLocalStorageValue('pendulumAngle')) || startAngle || 0; // Use startAngle if pendulumAngle isn't set
// --- UI Initialization ---
// Call this *after* loading all settings from localStorage
function initializeUI() {
// Set control values from loaded settings
document.getElementById('line-color').value = color;
document.getElementById('special-line-color').value = color2;
document.getElementById('circle-outline-color').value = color3;
document.getElementById('bg-color').value = bgColor;
document.getElementById('text-color').value = textColor;
document.getElementById('line-thickness').value = lineThickness;
document.getElementById('radiating-line-count').value = radiatingLineCount;
document.getElementById('horizontal-offset').value = horizontalOffset;
document.getElementById('vertical-offset').value = verticalOffset;
document.getElementById('arc-offset').value = arcOffset;
document.getElementById('line-length').value = lineLength;
document.getElementById('text-size').value = textSize;
document.getElementById('pendulum-thickness').value = pendulumThickness;
document.getElementById('text-distance').value = textDistance;
document.getElementById('rotation-velocity').value = rotationVelocity;
document.getElementById('autopilot-speed').value = autopilotSpeed;
document.getElementById('rotate-clockwise').checked = rotateClockwise;
document.getElementById('rotate-counterclockwise').checked = rotateCounterclockwise;
document.getElementById('opacity-slider').value = opacity;
document.getElementById('visualization-mode').value = mode;
document.getElementById('autopilot-walk-range').value = autopilotWalkRange;
document.getElementById('circle-outline-dash-density').value = circleOutlineDashDensity;
document.getElementById('depth-offset').value = depthOffset;
document.getElementById('anaglyph-left-color').value = anaglyphLeftColor;
document.getElementById('anaglyph-right-color').value = anaglyphRightColor;
// Apply initial state
setBackgroundColor(bgColor);
applyDarkMode(isDarkMode); // Apply dark mode based on loaded setting
controls.style.opacity = opacity;
toggleControlVisibility(); // Set visibility based on loaded mode
updateTextPlaceholder(); // Set label text based on loaded mode
setSliderLimits(); // Set limits based on loaded walk range
// Position controls container
const controlsContainer = document.getElementById('controls-container');
const savedPosition = JSON.parse(getLocalStorageValue('controlsPosition') || '{}'); // Default to empty obj
const initialX = savedPosition.x !== undefined ? savedPosition.x : defaultSettings.controlsPosition.x;
const initialY = savedPosition.y !== undefined ? savedPosition.y : defaultSettings.controlsPosition.y;
controlsContainer.style.transform = `translate(${initialX}px, ${initialY}px)`;
controlsContainer.setAttribute('data-x', initialX);
controlsContainer.setAttribute('data-y', initialY);
if (isReversed) {
controlsContainer.classList.add('reverse');
}
// Initialize Pan/Zoom AFTER UI elements are ready
initializeZoomAndPan();
// Set initial transform based on loaded scale/origin (if we were saving them)
// For now, we start centered and non-zoomed, handled by initializeZoomAndPan defaults
updateCanvasTransform(); // Apply initial transform (center, scale=1)
// Initial draw on page load
requestAnimationFrame(draw); // Use rAF for initial draw
}
// --- Event Listeners ---
document.addEventListener('DOMContentLoaded', initializeUI);
// Make controls draggable
interact('.draggable').draggable({
allowFrom: '#drag-handle', // Only allow dragging from the handle
inertia: true, // Add some inertia
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent', // Keep within the body/window
endOnly: true // Apply restriction only at the end of drag
})
],
autoScroll: false, // Usually not needed for a small controls box
listeners: {
move(event) { // Use the move event directly
const target = event.target;
// Keep the dragged position in the data-x/data-y attributes
const x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
const y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// Translate the element
target.style.transform = `translate(${x}px, ${y}px)`;
// Update the position attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
},
end(event) { // Save position when dragging ends
const target = event.target;
const x = parseFloat(target.getAttribute('data-x')) || 0;
const y = parseFloat(target.getAttribute('data-y')) || 0;
setLocalStorageValue('controlsPosition', JSON.stringify({ x: x, y: y }));
}
}
});
// --- Controls and Event Listeners ---
const controls = document.getElementById('controls');
const toggleMenuButton = document.getElementById('toggle-menu');
const flipPositionButton = document.getElementById('flip-position');
const controlsContainer = document.getElementById('controls-container');
toggleMenuButton.addEventListener('click', () => {
const isVisible = controls.style.display === 'block';
controls.style.display = isVisible ? 'none' : 'block';
toggleMenuButton.textContent = isVisible ? 'Show Controls' : 'Hide Controls';
toggleMenuButton.setAttribute('aria-expanded', !isVisible); // ARIA attribute
});
// Set initial ARIA state for controls visibility
toggleMenuButton.setAttribute('aria-expanded', controls.style.display === 'block');
controls.setAttribute('aria-hidden', controls.style.display !== 'block'); // Hide from screen readers when not visible
flipPositionButton.addEventListener('click', () => {
isReversed = !isReversed;
setLocalStorageValue('isReversed', isReversed); // Correct LS key
controlsContainer.classList.toggle('reverse');
});
const horizontalOffsetSlider = document.getElementById('horizontal-offset');
const verticalOffsetSlider = document.getElementById('vertical-offset');
const autopilotWalkRangeSlider = document.getElementById('autopilot-walk-range');
function setSliderLimits() {
// Base limits on canvas size directly, walk range controls *behavior*
const maxX = Math.floor(canvasWidth * 1.5); // Allow going off-screen
const maxY = Math.floor(canvasHeight * 1.5);
horizontalOffsetSlider.min = -maxX;
horizontalOffsetSlider.max = maxX;
verticalOffsetSlider.min = -maxY;
verticalOffsetSlider.max = maxY;
// Clamp current value if it falls outside new limits (can happen on resize)
horizontalOffset = Math.max(parseInt(horizontalOffsetSlider.min), Math.min(horizontalOffset, parseInt(horizontalOffsetSlider.max)));
verticalOffset = Math.max(parseInt(verticalOffsetSlider.min), Math.min(verticalOffset, parseInt(verticalOffsetSlider.max)));
// Update slider positions to reflect potentially clamped values
horizontalOffsetSlider.value = horizontalOffset;
verticalOffsetSlider.value = verticalOffset;
}
// Function to calculate Anaglyph colors based on the background
function calculateAnaglyphColors(bgHexColor) {
// Ensure bgHexColor is a 6-digit hex
bgHexColor = standardize_color(bgHexColor);
if (!bgHexColor || bgHexColor.length !== 7) {
console.warn("Invalid background color for anaglyph calculation:", bgHexColor);
return { left: '#ff0000', right: '#00ffff' }; // Return defaults
}