-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
973 lines (911 loc) · 38.4 KB
/
main.js
File metadata and controls
973 lines (911 loc) · 38.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
// === Vector Mandala Maker Main Logic ===
// This file manages both the border/background shape (always present, not a drawing tool)
// and the interactive drawing tools (freehand, line, ellipse, regular polygon, weird polygon, irregular polygon, etc).
// Border/background controls are separate from drawing tool controls.
// (All DOM element access and event listeners are now inside DOMContentLoaded. Only functions/vars outside.)
function getSVGCoords(e) {
const rect = svg.getBoundingClientRect();
// Use viewBox for scaling
let vb = svg.viewBox && svg.viewBox.baseVal ? svg.viewBox.baseVal : {x:0, y:0, width:svg.width.baseVal.value, height:svg.height.baseVal.value};
return {
x: ((e.clientX - rect.left) / rect.width) * vb.width + vb.x,
y: ((e.clientY - rect.top) / rect.height) * vb.height + vb.y
};
}
// === BEGIN AUTOFILLCOLOR & COLOR_SWATCHES LOGIC ===
// Move all DOM-dependent code inside DOMContentLoaded
let svg;
let controls;
let strokeColor;
let fillColor;
let autoFillColorToggle;
let strokeWidth;
let symmetryAxes;
let clearBtn;
let downloadBtn;
let borderFill;
let borderEdgeColor;
let borderWidth;
let borderShapeType;
let borderPolySides;
let borderPolySidesLabel;
let AutoFillColor = true;
let COLOR_SWATCHES;
let pickRandomSwatchColor;
let setRandomFillColor;
// --- Drawing Tool State (must be defined before any function uses them) ---
let currentTool = 'freehand';
let drawing = false;
let startPoint = null;
let currentPath = null;
let weirdPolygonPoints = [];
let weirdPolygonDrawing = false;
let irregularPolygonPoints = [];
let irregularPolygonDrawing = false;
document.addEventListener('DOMContentLoaded', () => {
// DOM references
svg = document.getElementById('mandalaCanvas');
controls = document.getElementById('controls');
strokeColor = document.getElementById('strokeColor');
fillColor = document.getElementById('fillColor');
autoFillColorToggle = document.getElementById('autoFillColorToggle');
strokeWidth = document.getElementById('strokeWidth');
symmetryAxes = document.getElementById('symmetryAxes');
clearBtn = document.getElementById('clearBtn');
downloadBtn = document.getElementById('downloadBtn');
borderFill = document.getElementById('borderFill');
borderEdgeColor = document.getElementById('borderEdgeColor');
borderWidth = document.getElementById('borderWidth');
borderShapeType = document.getElementById('borderShapeType');
borderPolySides = document.getElementById('borderPolySides');
borderPolySidesLabel = document.getElementById('borderPolySidesLabel');
// Basic palette of common colors
COLOR_SWATCHES = [
'#000000', '#ffffff', '#e53935', '#d81b60', '#8e24aa', '#3949ab',
'#1e88e5', '#00897b', '#43a047', '#fbc02d', '#fb8c00', '#6d4c41',
'#bdbdbd', '#757575', '#00bcd4', '#cddc39'
];
pickRandomSwatchColor = function() {
return COLOR_SWATCHES[Math.floor(Math.random() * COLOR_SWATCHES.length)];
};
setRandomFillColor = function() {
const color = pickRandomSwatchColor();
fillColor.value = color;
fillColor.dispatchEvent(new Event('input', { bubbles: true }));
};
// Listen for toggle
if (autoFillColorToggle) {
autoFillColorToggle.checked = true;
autoFillColorToggle.addEventListener('change', () => {
AutoFillColor = autoFillColorToggle.checked;
});
}
AutoFillColor = autoFillColorToggle ? autoFillColorToggle.checked : true;
// On startup, set initial fill color if AutoFillColor is enabled
if (AutoFillColor) {
setRandomFillColor();
}
// Color swatch UI
createColorSwatches('strokeSwatches', strokeColor);
createColorSwatches('fillSwatches', fillColor);
// Border/background controls event listeners
function redrawBorder() {
setupBgAndBorderRects();
updateBgAndBorder();
console.log('[VectorMandala] Border shape redrawn');
}
borderFill.addEventListener('input', redrawBorder);
borderEdgeColor.addEventListener('input', redrawBorder);
borderWidth.addEventListener('input', redrawBorder);
borderShapeType.addEventListener('change', () => {
// Enable/disable polygon sides
if (borderShapeType.value === 'polygon') {
borderPolySides.disabled = false;
borderPolySidesLabel.style.opacity = 1;
} else {
borderPolySides.disabled = true;
borderPolySidesLabel.style.opacity = 0.5;
}
redrawBorder();
});
borderPolySides.addEventListener('input', redrawBorder);
// Set initial state for polygon sides
if (borderShapeType.value === 'polygon') {
borderPolySides.disabled = false;
borderPolySidesLabel.style.opacity = 1;
} else {
borderPolySides.disabled = true;
borderPolySidesLabel.style.opacity = 0.5;
}
// Initial draw
redrawBorder();
console.log('[VectorMandala] Initialization complete');
// Drawing tool listeners (example for color)
strokeColor.addEventListener('input', () => {
if (selectedShape) updateSelectedShapeStyle();
});
fillColor.addEventListener('input', () => {
if (selectedShape) updateSelectedShapeStyle();
});
// Add more listeners as needed for drawing tools, clear, download, etc.
// Example: Clear button
if (clearBtn) {
clearBtn.addEventListener('click', () => {
Array.from(svg.children).forEach(el => el.remove());
saveHistory();
});
}
// Example: Download button
if (downloadBtn) {
downloadBtn.addEventListener('click', () => {
// Download SVG logic here
});
}
// ... Add any additional setup or listeners needed for your tools ...
// --- Drawing Tool Button Event Handling ---
if (controls) {
controls.addEventListener('click', e => {
if (e.target.matches('button[data-tool]')) {
setActiveTool(e.target.dataset.tool);
}
});
}
if (svg) {
svg.addEventListener('mousedown', e => {
console.log('[mousedown] tool:', currentTool);
if (e.button !== 0) return;
const { x, y } = getSVGCoords(e);
startPoint = { x, y };
// Capture style for this shape
currentShapeStyle = {
stroke: strokeColor.value,
fill: fillColor.value,
strokeWidth: strokeWidth.value
};
if (currentTool === 'freehand') {
drawing = true;
currentPath = [{ x, y }];
drawPreview();
} else if (currentTool === 'line' || currentTool === 'ellipse') {
drawing = true;
drawPreview({ x, y });
} else if (currentTool === 'polygon-regular') {
drawing = true;
drawPreview({ x, y });
} else if (currentTool === 'weird-polygon') {
weirdPolygonDrawing = true;
weirdPolygonPoints = [{ x, y }];
drawPreview({ x, y });
} else if (currentTool === 'polygon-irregular') {
irregularPolygonDrawing = true;
irregularPolygonPoints = [{ x, y }];
drawPreview({ x, y });
}
});
}
// --- Drawing Preview on Mouse Move ---
if (svg) {
svg.addEventListener('mousemove', e => {
if (currentTool === 'polygon-irregular' && irregularPolygonDrawing) {
const { x, y } = getSVGCoords(e);
irregularPolygonPoints.push({ x, y });
drawPreview({ x, y });
return;
}
if (!drawing) return;
const { x, y } = getSVGCoords(e);
if (currentTool === 'freehand' && currentPath) {
currentPath.push({ x, y });
drawPreview();
} else if (currentTool === 'polygon-regular' && startPoint) {
drawPreview({ x, y });
} else if (currentTool === 'line' || currentTool === 'ellipse') {
drawPreview({ x, y });
} else if (currentTool === 'weird-polygon' && weirdPolygonDrawing) {
weirdPolygonPoints.push({ x, y });
drawPreview({ x, y });
}
});
svg.addEventListener('mouseup', e => {
if (!drawing && !weirdPolygonDrawing && !irregularPolygonDrawing) return;
const { x, y } = getSVGCoords(e);
if (currentTool === 'freehand' && currentPath) {
drawing = false;
commitFreehand(currentPath, currentShapeStyle);
currentPath = null;
} else if (currentTool === 'line') {
drawing = false;
commitLine(startPoint, { x, y }, currentShapeStyle);
startPoint = null;
} else if (currentTool === 'ellipse') {
drawing = false;
commitEllipse(startPoint, { x, y }, currentShapeStyle);
startPoint = null;
} else if (currentTool === 'polygon-regular') {
drawing = false;
commitRegularPolygon(startPoint, { x, y }, regularPolySides, currentShapeStyle);
startPoint = null;
} else if (currentTool === 'weird-polygon' && weirdPolygonDrawing) {
weirdPolygonPoints.push({ x, y });
commitWeirdPolygon(weirdPolygonPoints, currentShapeStyle);
weirdPolygonDrawing = false;
weirdPolygonPoints = [];
} else if (currentTool === 'polygon-irregular' && irregularPolygonDrawing) {
irregularPolygonPoints.push({ x, y });
commitSymmetricIrregularPolygon(irregularPolygonPoints, currentShapeStyle);
irregularPolygonDrawing = false;
irregularPolygonPoints = [];
}
drawPreview();
});
}
const undoBtn = document.getElementById('undoBtn');
if (undoBtn) undoBtn.addEventListener('click', undo);
const redoBtn = document.getElementById('redoBtn');
if (redoBtn) redoBtn.addEventListener('click', redo);
const regularPolySidesInput = document.getElementById('regularPolySides');
if (regularPolySidesInput) {
regularPolySidesInput.addEventListener('input', e => {
regularPolySides = Math.max(3, Math.floor(e.target.value));
});
}
// --- END Drawing Tool Button Event Handling ---
// Sync borderPolySides to symmetryAxes at startup
if (borderPolySides && symmetryAxes) {
borderPolySides.value = symmetryAxes.value;
}
setupBgAndBorderRects();
updateBgAndBorder();
drawSymmetryAxes();
resizeSVGToFit();
setActiveTool('freehand');
if (typeof updateRegularPolySidesVisibility === 'function') updateRegularPolySidesVisibility();
saveHistory();
// Listen for axes toggle
const showAxes = document.getElementById('showAxes');
if (showAxes) {
showAxes.addEventListener('change', drawSymmetryAxes);
}
// Keep borderPolySides in sync with symmetryAxes on change
if (symmetryAxes && borderPolySides) {
symmetryAxes.addEventListener('input', (e) => {
borderPolySides.value = e.target.value;
});
}
});
// === END AUTOFILLCOLOR & COLOR_SWATCHES LOGIC ===
// === BEGIN COLOR SWATCHES LOGIC (now inside DOMContentLoaded) ===
// (All color swatch logic is now inside DOMContentLoaded to avoid redeclaration errors)
function createColorSwatches(containerId, inputEl) {
const container = document.getElementById(containerId);
if (!container) return;
container.innerHTML = '';
COLOR_SWATCHES.forEach(color => {
const swatch = document.createElement('div');
swatch.style.background = color;
swatch.style.width = '22px';
swatch.style.height = '22px';
swatch.style.border = '2px solid #aaa';
swatch.style.borderRadius = '4px';
swatch.style.cursor = 'pointer';
swatch.style.transition = 'border 0.15s';
swatch.title = color;
// Highlight selected color
function updateHighlight() {
swatch.style.border = (inputEl.value.toLowerCase() === color.toLowerCase()) ? '3px solid #1976d2' : '2px solid #aaa';
}
inputEl.addEventListener('input', updateHighlight);
swatch.addEventListener('click', () => {
inputEl.value = color;
inputEl.dispatchEvent(new Event('input', { bubbles: true }));
updateHighlight();
});
updateHighlight();
container.appendChild(swatch);
});
// Update highlights when color is changed elsewhere
inputEl.addEventListener('change', () => {
Array.from(container.children).forEach(child => {
child.style.border = (inputEl.value.toLowerCase() === child.title.toLowerCase()) ? '3px solid #1976d2' : '2px solid #aaa';
});
});
}
// === END COLOR SWATCHES LOGIC ===
// (All border/background control initialization and event listeners are now inside DOMContentLoaded. Remove global declarations.)
let selectedShape = null;
let backgroundRect = null;
let backgroundCircle = null;
let backgroundPolygon = null;
let borderRect = null;
// Insert background and border rects
// --- Border/Background Shape Drawing ---
// Draws the border/background shape according to border controls. Not a drawing tool.
function setupBgAndBorderRects() {
// Remove symmetry axes if present (they will be redrawn if needed)
Array.from(svg.querySelectorAll('.symmetry-axis')).forEach(el => el.remove());
drawSymmetryAxes();
// Remove existing border shape if present
Array.from(svg.querySelectorAll('.border-rect')).forEach(el => el.remove());
const shapeType = borderShapeType.value;
// Get SVG size from viewBox or bounding rect
let width = 800, height = 800;
if (svg.viewBox && svg.viewBox.baseVal && svg.viewBox.baseVal.width) {
width = svg.viewBox.baseVal.width;
height = svg.viewBox.baseVal.height;
} else if (svg.width && svg.height) {
width = svg.width.baseVal.value;
height = svg.height.baseVal.value;
} else {
const rect = svg.getBoundingClientRect();
width = rect.width;
height = rect.height;
}
const size = Math.min(width, height);
// Draw background shape with border
// Draw border shape only (as first SVG child)
let borderShape = null;
if (shapeType === 'square') {
const inset = borderWidth.value / 2;
borderShape = createSVGElement('rect', {
x: (width - size) / 2 + inset, y: (height - size) / 2 + inset, width: size - borderWidth.value, height: size - borderWidth.value,
fill: borderFill.value,
stroke: borderEdgeColor.value,
'stroke-width': borderWidth.value,
class: 'border-rect'
});
svg.insertBefore(borderShape, svg.firstChild);
} else if (shapeType === 'circle') {
const inset = borderWidth.value / 2;
const center = getSVGCenter();
borderShape = createSVGElement('circle', {
cx: center.x, cy: center.y, r: (size / 2) - inset,
fill: borderFill.value,
stroke: borderEdgeColor.value,
'stroke-width': borderWidth.value,
class: 'border-rect'
});
svg.insertBefore(borderShape, svg.firstChild);
} else if (shapeType === 'polygon') {
const sides = Math.max(3, Math.floor(borderPolySides.value));
const center = getSVGCenter();
const r = (size / 2) - (borderWidth.value / 2);
let points = [];
for (let i = 0; i < sides; i++) {
const angle = 2 * Math.PI * i / sides - Math.PI / 2;
const x = center.x + r * Math.cos(angle);
const y = center.y + r * Math.sin(angle);
points.push(`${x},${y}`);
}
borderShape = createSVGElement('polygon', {
points: points.join(' '),
fill: borderFill.value,
stroke: borderEdgeColor.value,
'stroke-width': borderWidth.value,
class: 'border-rect'
});
svg.insertBefore(borderShape, svg.firstChild);
}
borderRect = borderShape;
}
function updateBgAndBorder() {
// Update fill, stroke, and stroke-width for border shape
if (borderRect) {
borderRect.setAttribute('fill', borderFill.value);
borderRect.setAttribute('stroke', borderEdgeColor.value);
borderRect.setAttribute('stroke-width', borderWidth.value);
}
}
function resizeSVGToFit() {
const controls = document.getElementById('controls');
const container = document.getElementById('canvasContainer');
const toolbarHeight = controls.offsetHeight;
const availableHeight = window.innerHeight - toolbarHeight - 24; // 24px for margin
const availableWidth = container.offsetWidth || window.innerWidth;
const size = Math.min(availableWidth, availableHeight);
svg.setAttribute('width', size);
svg.setAttribute('height', size);
svg.setAttribute('viewBox', `0 0 ${size} ${size}`);
svg.style.display = 'block';
setupBgAndBorderRects();
updateBgAndBorder();
}
// Removed second DOMContentLoaded handler
window.addEventListener('resize', () => {
resizeSVGToFit();
drawSymmetryAxes();
});
function drawSymmetryAxes() {
// Remove old axes
Array.from(svg.querySelectorAll('.symmetry-axis')).forEach(el => el.remove());
const showAxes = document.getElementById('showAxes');
const symmetryAxes = document.getElementById('symmetryAxes');
if (!showAxes || !showAxes.checked || !symmetryAxes) return;
const axes = parseInt(symmetryAxes.value);
if (!axes || axes < 2) return;
const center = getSVGCenter();
// Use radius as half the minimum of width/height
let width = 800, height = 800;
if (svg.viewBox && svg.viewBox.baseVal && svg.viewBox.baseVal.width) {
width = svg.viewBox.baseVal.width;
height = svg.viewBox.baseVal.height;
} else if (svg.width && svg.height) {
width = svg.width.baseVal.value;
height = svg.height.baseVal.value;
} else {
const rect = svg.getBoundingClientRect();
width = rect.width;
height = rect.height;
}
const r = Math.min(width, height) / 2;
for (let i = 0; i < axes; i++) {
const angle = (2 * Math.PI * i) / axes;
const x2 = center.x + r * Math.cos(angle);
const y2 = center.y + r * Math.sin(angle);
const axis = createSVGElement('line', {
x1: center.x, y1: center.y, x2: x2, y2: y2,
stroke: '#888',
'stroke-width': 1,
'stroke-dasharray': '6 6',
class: 'symmetry-axis'
});
svg.insertBefore(axis, svg.firstChild);
}
}
// Only border shape controls remain; bgColor, bgShapeType, etc. are obsolete and removed.
// (All event listeners and DOM accesses are now inside DOMContentLoaded handler above.)
function selectShape(shape) {
if (selectedShape) deselectShape();
selectedShape = shape;
shape.classList.add('selected');
// Update controls to match shape
if (shape.hasAttribute('stroke')) strokeColor.value = shape.getAttribute('stroke');
if (shape.hasAttribute('fill')) fillColor.value = shape.getAttribute('fill');
if (shape.hasAttribute('stroke-width')) strokeWidth.value = shape.getAttribute('stroke-width');
}
function deselectShape() {
if (selectedShape) selectedShape.classList.remove('selected');
selectedShape = null;
}
function updateSelectedShapeStyle() {
if (!selectedShape) return;
if (selectedShape.hasAttribute('stroke')) selectedShape.setAttribute('stroke', strokeColor.value);
if (selectedShape.hasAttribute('fill')) selectedShape.setAttribute('fill', fillColor.value);
if (selectedShape.hasAttribute('stroke-width')) selectedShape.setAttribute('stroke-width', strokeWidth.value);
}
let regularPolySides = 6;
let currentShapeStyle = {};
let undoStack = [];
let redoStack = [];
// --- Function declarations (move all above DOMContentLoaded) ---
function saveHistory() {
const shapes = Array.from(svg.children).filter(el => !el.classList.contains('bg-rect') && !el.classList.contains('border-rect'));
const snapshot = shapes.map(el => el.outerHTML);
if (undoStack.length === 0 || JSON.stringify(undoStack[undoStack.length - 1]) !== JSON.stringify(snapshot)) {
undoStack.push(snapshot);
redoStack = [];
const children = Array.from(svg.children).map(el => el.tagName + ' ' + el.getAttribute('class'));
console.log('[saveHistory] New snapshot saved. Undo stack length:', undoStack.length, 'SVG children:', children, 'Stack:', JSON.stringify(undoStack));
} else {
const children = Array.from(svg.children).map(el => el.tagName + ' ' + el.getAttribute('class'));
console.log('[saveHistory] Snapshot identical to last. No push. Undo stack length:', undoStack.length, 'SVG children:', children);
}
}
function restoreHistory(snapshot) {
Array.from(svg.children).forEach(el => {
if (!el.classList.contains('bg-rect') && !el.classList.contains('border-rect')) el.remove();
});
snapshot.forEach(html => {
const temp = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
temp.innerHTML = html;
const node = temp.firstElementChild;
if (node) svg.appendChild(node);
});
setupBgAndBorderRects();
updateBgAndBorder();
const children = Array.from(svg.children).map(el => el.tagName + ' ' + el.getAttribute('class'));
console.log('[restoreHistory] SVG children after restore:', children, 'Snapshot:', snapshot);
}
function undo() {
if (undoStack.length <= 1) return;
const current = undoStack.pop();
redoStack.push(current);
const prev = undoStack[undoStack.length - 1];
restoreHistory(prev);
deselectShape();
}
function redo() {
if (!redoStack.length) return;
const next = redoStack.pop();
undoStack.push(next);
restoreHistory(next);
deselectShape();
}
// Always-visible input for regular polygon sides
const regularPolySidesInput = document.getElementById('regularPolySides');
if (regularPolySidesInput) {
regularPolySidesInput.addEventListener('input', e => {
regularPolySides = Math.max(3, Math.floor(e.target.value));
});
}
function getSVGCenter() {
// Computes the true center of the SVG based on viewBox or width/height
let width = 800, height = 800;
if (svg.viewBox && svg.viewBox.baseVal && svg.viewBox.baseVal.width) {
width = svg.viewBox.baseVal.width;
height = svg.viewBox.baseVal.height;
} else if (svg.width && svg.height) {
width = svg.width.baseVal.value;
height = svg.height.baseVal.value;
} else {
const rect = svg.getBoundingClientRect();
width = rect.width;
height = rect.height;
}
return { x: width / 2, y: height / 2 };
}
function getSymmetryPoints(x, y, cx, cy, axes) {
// Returns an array of points rotated around the center
const points = [];
const angleStep = (2 * Math.PI) / axes;
for (let i = 0; i < axes; i++) {
const angle = angleStep * i;
const dx = x - cx;
const dy = y - cy;
const rx = Math.cos(angle) * dx - Math.sin(angle) * dy + cx;
const ry = Math.sin(angle) * dx + Math.cos(angle) * dy + cy;
points.push({ x: rx, y: ry });
}
return points;
}
function createSVGElement(tag, attrs) {
const el = document.createElementNS('http://www.w3.org/2000/svg', tag);
for (const k in attrs) {
el.setAttribute(k, attrs[k]);
}
return el;
}
// --- Drawing Tool Selection ---
// Handles switching between drawing tools and showing/hiding their controls.
function setActiveTool(tool) {
console.log('[DIAG] setActiveTool called with', tool);
currentTool = tool;
Array.from(controls.querySelectorAll('button[data-tool]')).forEach(btn => {
btn.classList.toggle('active', btn.dataset.tool === tool);
});
// --- Commit in-progress weird polygon if needed ---
if (weirdPolygonDrawing && weirdPolygonPoints.length > 1) {
// Ensure the last mouse position is included if not already
if (typeof mousePos !== 'undefined' && mousePos && weirdPolygonPoints.length > 0) {
const last = weirdPolygonPoints[weirdPolygonPoints.length - 1];
if (last.x !== mousePos.x || last.y !== mousePos.y) {
weirdPolygonPoints.push({x: mousePos.x, y: mousePos.y});
}
}
commitWeirdPolygon([...weirdPolygonPoints], currentShapeStyle);
}
// --- Commit in-progress irregular polygon if needed ---
if (irregularPolygonDrawing && irregularPolygonPoints.length > 2) {
commitSymmetricIrregularPolygon(irregularPolygonPoints, currentShapeStyle);
}
// Reset all tool-specific state
drawing = false;
startPoint = null;
currentPath = null;
weirdPolygonPoints = [];
weirdPolygonDrawing = false;
irregularPolygonPoints = [];
irregularPolygonDrawing = false;
// Only clear currentPath for non-freehand tools
if (currentTool !== 'freehand') currentPath = null;
// Only clear preview shapes, not committed shapes
Array.from(svg.querySelectorAll('.preview')).forEach(el => el.remove());
drawPreview(); // Clear any preview
}
// --- Drawing Tool Button Event Handling ---
// (drawing logic is now only inside svg.addEventListener('mousedown', ...) in DOMContentLoaded)
// ESCAPE KEY: Finish (commit) irregular polygon if drawing
window.addEventListener('keydown', e => {
if (e.key === 'Escape' && irregularPolygonDrawing) {
if (irregularPolygonPoints.length > 2) {
commitSymmetricIrregularPolygon(irregularPolygonPoints, currentShapeStyle);
}
irregularPolygonPoints = [];
irregularPolygonDrawing = false;
drawPreview();
}
});
// --- Main Drawing Logic: Mouse Up ---
svg.addEventListener('mouseup', e => {
console.log('[mouseup] tool:', currentTool, 'drawing:', drawing);
if (!drawing) return;
drawing = false;
const { x, y } = getSVGCoords(e);
if (currentTool === 'freehand' && currentPath) {
currentPath.push({ x, y });
console.log('[mouseup] committing freehand currentPath:', currentPath);
commitFreehand(currentPath, currentShapeStyle);
currentPath = null;
} else if (currentTool === 'polygon-regular' && startPoint) {
commitRegularPolygon(startPoint, { x, y }, regularPolySides, currentShapeStyle);
} else if (currentTool === 'line') {
commitLine(startPoint, { x, y }, currentShapeStyle);
} else if (currentTool === 'ellipse') {
commitEllipse(startPoint, { x, y }, currentShapeStyle);
}
// For irregular polygon: use double-click to finish
});
// --- Main Drawing Logic: Double Click (for polygons) ---
svg.addEventListener('dblclick', e => {
if (currentTool === 'weird-polygon' && weirdPolygonDrawing) {
if (weirdPolygonPoints.length > 1) {
// Ensure the last mouse position is included if not already
if (typeof mousePos !== 'undefined' && mousePos && weirdPolygonPoints.length > 0) {
const last = weirdPolygonPoints[weirdPolygonPoints.length - 1];
if (last.x !== mousePos.x || last.y !== mousePos.y) {
weirdPolygonPoints.push({x: mousePos.x, y: mousePos.y});
}
}
commitWeirdPolygon([...weirdPolygonPoints], currentShapeStyle);
}
weirdPolygonPoints = [];
drawPreview();
} else if (currentTool === 'polygon-irregular' && irregularPolygonDrawing) {
// Double-click to close and commit with symmetry
if (irregularPolygonPoints.length > 2) {
commitSymmetricIrregularPolygon(irregularPolygonPoints, currentShapeStyle);
}
irregularPolygonPoints = [];
irregularPolygonDrawing = false;
drawPreview();
}
});
// --- Drawing Preview for All Tools ---
function commitWeirdPolygon(points, style) {
console.log('[commitWeirdPolygon] called with', points, style);
if (points.length < 2) return;
const axes = parseInt(symmetryAxes.value);
const center = getSVGCenter();
drawSymmetricWeirdPolygon(points, axes, center, false, style);
saveHistory();
if (AutoFillColor) setRandomFillColor();
console.log('[commitWeirdPolygon] finished, called saveHistory');
}
function drawPreview(mousePos) {
console.log('[drawPreview] tool:', currentTool, 'drawing:', drawing, 'currentPath:', currentPath, 'mousePos:', mousePos);
// Remove previous preview
Array.from(svg.querySelectorAll('.preview')).forEach(el => el.remove());
const axes = parseInt(symmetryAxes.value);
const center = getSVGCenter();
if (currentTool === 'freehand' && currentPath) {
console.log('[drawPreview] drawing freehand preview path');
drawSymmetricPaths(currentPath, axes, center, true, currentShapeStyle);
} else if ((currentTool === 'line' || currentTool === 'ellipse') && drawing && startPoint && mousePos) {
if (currentTool === 'line') {
drawSymmetricLine(startPoint, mousePos, axes, center, true, currentShapeStyle);
} else {
drawSymmetricEllipse(startPoint, mousePos, axes, center, true, currentShapeStyle);
}
} else if (currentTool === 'weird-polygon' && weirdPolygonDrawing && weirdPolygonPoints.length) {
let points = [...weirdPolygonPoints];
if (mousePos) points.push(mousePos);
drawSymmetricWeirdPolygon(points, axes, center, true, currentShapeStyle);
} else if (currentTool === 'polygon-irregular' && irregularPolygonDrawing && irregularPolygonPoints.length) {
let points = [...irregularPolygonPoints];
if (mousePos) points.push(mousePos);
drawSymmetricIrregularPolygon(points, axes, center, true, currentShapeStyle);
// Draw a small preview circle at the first point to indicate closing area
const first = irregularPolygonPoints[0];
const circle = createSVGElement('circle', {
cx: first.x,
cy: first.y,
r: 7,
fill: 'none',
stroke: '#00ff00',
'stroke-width': 2,
class: 'preview'
});
svg.appendChild(circle);
// The following code draws a path for irregular polygons only. It should NOT run for 'polygon-regular'.
// (No code here for regular polygon)
} else if (currentTool === 'polygon-regular' && drawing && startPoint && mousePos) {
console.log('[drawPreview] drawing regular polygon preview, regularPolySides:', regularPolySides);
if (regularPolySides >= 3) {
drawSymmetricRegularPolygon(startPoint, mousePos, regularPolySides, axes, center, true, currentShapeStyle);
} else {
console.log('[drawPreview] NOT drawing: regularPolySides < 3');
}
}
}
function commitFreehand(points, style) {
const axes = parseInt(symmetryAxes.value);
const center = getSVGCenter();
drawSymmetricPaths(points, axes, center, false, style);
saveHistory();
if (AutoFillColor) setRandomFillColor();
}
function commitLine(p1, p2, style) {
console.log('[commitLine] called with', p1, p2, style);
// Only draw and save if points are different
if (p1.x !== p2.x || p1.y !== p2.y) {
const axes = parseInt(symmetryAxes.value);
const center = getSVGCenter();
drawSymmetricLine(p1, p2, axes, center, false, style);
saveHistory();
} else {
console.log('[commitLine] Skipped: start and end points are identical');
}
}
function commitEllipse(p1, p2, style) {
const axes = parseInt(symmetryAxes.value);
const center = getSVGCenter();
drawSymmetricEllipse(p1, p2, axes, center, false, style);
saveHistory();
if (AutoFillColor) setRandomFillColor();
}
// Commit the drawn irregular polygon as a filled SVG path
// Commit the drawn irregular polygon as a filled SVG path with symmetry
function commitSymmetricIrregularPolygon(points, style) {
if (points.length < 3) return;
const axes = parseInt(symmetryAxes.value);
const center = getSVGCenter();
drawSymmetricIrregularPolygon(points, axes, center, false, style);
saveHistory();
}
function commitRegularPolygon(centerPt, edgePt, sides, style) {
const axes = parseInt(symmetryAxes.value);
const center = getSVGCenter();
drawSymmetricRegularPolygon(centerPt, edgePt, sides, axes, center, false, style);
saveHistory();
if (AutoFillColor) setRandomFillColor();
}
function drawSymmetricPaths(points, axes, center, preview, style) {
for (let i = 0; i < axes; i++) {
const rotated = points.map(pt => rotatePoint(pt, center, i * 2 * Math.PI / axes));
const pathData = rotated.map((pt, j) => (j === 0 ? `M${pt.x},${pt.y}` : `L${pt.x},${pt.y}`)).join(' ');
const path = createSVGElement('path', {
d: pathData,
stroke: style?.stroke || strokeColor.value,
'stroke-width': style?.strokeWidth || strokeWidth.value,
fill: 'none',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
class: preview ? 'preview' : ''
});
svg.appendChild(path);
}
}
function drawSymmetricLine(p1, p2, axes, center, preview, style) {
for (let i = 0; i < axes; i++) {
const rp1 = rotatePoint(p1, center, i * 2 * Math.PI / axes);
const rp2 = rotatePoint(p2, center, i * 2 * Math.PI / axes);
const line = createSVGElement('line', {
x1: rp1.x, y1: rp1.y, x2: rp2.x, y2: rp2.y,
stroke: style?.stroke || strokeColor.value,
'stroke-width': style?.strokeWidth || strokeWidth.value,
class: preview ? 'preview' : ''
});
svg.appendChild(line);
}
}
function drawSymmetricEllipse(p1, p2, axes, center, preview, style) {
const rx = Math.abs(p2.x - p1.x) / 2;
const ry = Math.abs(p2.y - p1.y) / 2;
const cx = (p1.x + p2.x) / 2;
const cy = (p1.y + p2.y) / 2;
for (let i = 0; i < axes; i++) {
const rc = rotatePoint({ x: cx, y: cy }, center, i * 2 * Math.PI / axes);
// Calculate the angle from the center to the ellipse center
const angleRad = Math.atan2(rc.y - center.y, rc.x - center.x);
const angleDeg = angleRad * 180 / Math.PI;
const ellipse = createSVGElement('ellipse', {
cx: rc.x, cy: rc.y, rx, ry,
stroke: style?.stroke || strokeColor.value,
'stroke-width': style?.strokeWidth || strokeWidth.value,
fill: style?.fill || fillColor.value,
class: preview ? 'preview' : '',
transform: `rotate(${angleDeg},${rc.x},${rc.y})`
});
svg.appendChild(ellipse);
}
}
function drawSymmetricWeirdPolygon(points, axes, center, preview, style) {
if (points.length < 2) return;
for (let i = 0; i < axes; i++) {
const rotated = points.map(pt => rotatePoint(pt, center, i * 2 * Math.PI / axes));
const pathData = rotated.map((pt, j) => (j === 0 ? `M${pt.x},${pt.y}` : `L${pt.x},${pt.y}`)).join(' ') + ' Z';
const poly = createSVGElement('path', {
d: pathData,
stroke: style?.stroke || strokeColor.value,
'stroke-width': style?.strokeWidth || strokeWidth.value,
fill: style?.fill || fillColor.value,
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
class: preview ? 'preview' : ''
});
svg.appendChild(poly);
}
}
function drawSymmetricIrregularPolygon(points, axes, center, preview, style) {
if (points.length < 2) return;
for (let i = 0; i < axes; i++) {
const rotated = points.map(pt => rotatePoint(pt, center, i * 2 * Math.PI / axes));
const pathData = rotated.map((pt, j) => (j === 0 ? `M${pt.x},${pt.y}` : `L${pt.x},${pt.y}`)).join(' ') + ' Z';
const poly = createSVGElement('path', {
d: pathData,
stroke: style?.stroke || strokeColor.value,
'stroke-width': style?.strokeWidth || strokeWidth.value,
fill: style?.fill || fillColor.value,
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
class: preview ? 'preview' : ''
});
svg.appendChild(poly);
}
}
function drawSymmetricRegularPolygon(centerPt, edgePt, sides, axes, center, preview, style) {
console.log('[drawSymmetricRegularPolygon] sides:', sides);
if (sides < 3) return;
// Calculate radius
const dx = edgePt.x - centerPt.x;
const dy = edgePt.y - centerPt.y;
const radius = Math.sqrt(dx * dx + dy * dy);
const angle0 = Math.atan2(dy, dx);
for (let i = 0; i < axes; i++) {
const polyPoints = [];
for (let j = 0; j < sides; j++) {
const angle = angle0 + j * 2 * Math.PI / sides;
polyPoints.push({
x: centerPt.x + Math.cos(angle) * radius,
y: centerPt.y + Math.sin(angle) * radius
});
}
const rotatedPoly = polyPoints.map(pt => rotatePoint(pt, center, i * 2 * Math.PI / axes));
const pathData = rotatedPoly.map((pt, j) => (j === 0 ? `M${pt.x},${pt.y}` : `L${pt.x},${pt.y}`)).join(' ') + ' Z';
const poly = createSVGElement('path', {
d: pathData,
stroke: preview ? '#ff00ff' : (style?.stroke || strokeColor.value),
'stroke-width': style?.strokeWidth || strokeWidth.value,
fill: style?.fill || fillColor.value,
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
class: preview ? 'preview' : ''
});
svg.appendChild(poly);
}
}
function rotatePoint(pt, center, angle) {
const dx = pt.x - center.x;
const dy = pt.y - center.y;
const rx = Math.cos(angle) * dx - Math.sin(angle) * dy + center.x;
const ry = Math.sin(angle) * dx + Math.cos(angle) * dy + center.y;
return { x: rx, y: ry };
}
clearBtn.addEventListener('click', () => {
Array.from(svg.children).forEach(el => el.remove());
saveHistory();
});
downloadBtn.addEventListener('click', () => {
const serializer = new XMLSerializer();
let source = serializer.serializeToString(svg);
// Add XML declaration and SVG namespace if missing
if (!source.match(/^<\?xml/)) {
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
}
const url = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(source);
const a = document.createElement('a');
a.href = url;
a.download = 'mandala.svg';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
// Initial polygon sides state
if (borderShapeType.value === 'polygon') {
borderPolySides.disabled = false;
borderPolySidesLabel.style.opacity = 1;
} else {
borderPolySides.disabled = true;
borderPolySidesLabel.style.opacity = 0.5;
}
// Initial tool highlight
setActiveTool('freehand');