-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvectorizer_playground.html
More file actions
926 lines (815 loc) · 39.6 KB
/
Copy pathvectorizer_playground.html
File metadata and controls
926 lines (815 loc) · 39.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vector Art Generator</title>
<style>
:root {
--bg-color: #f4f4f9;
--accent-color: #2c3e50;
--active-tab-color: #ffffff;
--inactive-tab-color: #e0e0e0;
--status-green: #2ecc71;
--status-red: #e74c3c;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: var(--bg-color);
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
padding: 20px;
box-sizing: border-box;
color: #333;
}
header {
text-align: center;
margin-bottom: 20px;
}
h1 {
margin: 0 0 5px 0;
color: var(--accent-color);
}
/* --- Tabs --- */
.tab-container {
width: 100%;
max-width: 800px;
display: flex;
margin-bottom: 0;
}
.tab {
flex: 1;
padding: 12px;
text-align: center;
background-color: var(--inactive-tab-color);
cursor: pointer;
font-weight: 600;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
margin-right: 2px;
transition: background 0.2s;
color: #666;
}
.tab:last-child {
margin-right: 0;
}
.tab.active {
background-color: white;
color: var(--accent-color);
box-shadow: 0 -2px 5px rgba(0,0,0,0.05);
}
/* --- Controls --- */
.controls-wrapper {
background: white;
width: 100%;
max-width: 800px;
padding: 20px;
border-bottom-left-radius: 8px;
border-bottom-right-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-bottom: 20px;
box-sizing: border-box;
}
.controls {
display: flex;
gap: 20px;
align-items: center;
flex-wrap: wrap;
justify-content: center;
}
.control-group {
display: flex;
flex-direction: column;
gap: 5px;
min-width: 120px;
}
.mode-controls {
display: flex;
gap: 20px;
border-left: 1px solid #ddd;
padding-left: 20px;
}
/* Stats Display */
.stats-display {
font-variant-numeric: tabular-nums;
font-weight: 600;
color: var(--accent-color);
display: flex;
align-items: center;
gap: 8px;
}
.status-dot {
width: 12px;
height: 12px;
border-radius: 50%;
background-color: #ccc;
display: inline-block;
transition: background-color 0.3s;
}
.status-dot.ok { background-color: var(--status-green); }
.status-dot.limit { background-color: var(--status-red); }
label {
font-size: 0.8rem;
font-weight: 700;
color: #555;
text-transform: uppercase;
letter-spacing: 0.5px;
}
input[type="range"], select {
width: 100%;
cursor: pointer;
padding: 5px;
border-radius: 4px;
border: 1px solid #ccc;
}
.buttons {
margin-left: auto;
display: flex;
gap: 10px;
}
button {
background-color: var(--accent-color);
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
}
button:hover {
background-color: #445D75;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
/* --- Canvas --- */
#drop-zone {
position: relative;
width: 100%;
max-width: 1100px;
aspect-ratio: 11 / 8.5;
background-color: white;
border: 2px dashed #ccc;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
transition: border-color 0.2s;
}
#drop-zone.dragover {
border-color: var(--accent-color);
background-color: #eef2f5;
}
canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.instruction {
position: absolute;
pointer-events: none;
color: #999;
font-size: 1.2rem;
text-align: center;
line-height: 1.5;
}
.hidden {
display: none !important;
}
</style>
</head>
<body>
<header>
<h1>Vector Art Generator</h1>
<p>Convert images to 11x8.5" plotter-friendly vector art.</p>
</header>
<div class="tab-container">
<div class="tab active" data-mode="concentrics">Concentrics</div>
<div class="tab" data-mode="hatched">Hatched</div>
<div class="tab" data-mode="flow">Flow Field</div>
<div class="tab" data-mode="density">Feature Density</div>
<div class="tab" data-mode="edges">Edges</div>
</div>
<div class="controls-wrapper">
<div class="controls">
<div id="global-controls" class="control-group">
<label for="resolution">Grid Size / Line Len</label>
<input type="range" id="resolution" min="5" max="50" value="12">
</div>
<div id="hatched-controls" class="mode-controls hidden">
<div class="control-group">
<label for="max-lines">Max Density</label>
<input type="range" id="max-lines" min="2" max="20" value="8">
</div>
<div class="control-group">
<label for="angle-offset">Angle Offset</label>
<input type="range" id="angle-offset" min="0" max="90" value="0">
</div>
</div>
<div id="flow-controls" class="mode-controls hidden">
<div class="control-group">
<label for="flow-algo">Placement</label>
<select id="flow-algo">
<option value="grid">Regular Grid</option>
<option value="dither">Ostromoukhov's Dithering</option>
</select>
</div>
<div class="control-group">
<label for="flow-scale">Density / Scale</label>
<input type="range" id="flow-scale" min="0.1" max="2.0" step="0.1" value="1.0">
</div>
</div>
<div id="density-controls" class="mode-controls hidden">
<div class="control-group">
<label for="density-radius">Feature Size</label>
<input type="range" id="density-radius" min="2" max="50" value="10">
</div>
<div class="control-group">
<label for="density-contrast">Intensity</label>
<input type="range" id="density-contrast" min="1" max="50" value="15">
</div>
</div>
<div id="edges-controls" class="mode-controls hidden">
<div class="control-group">
<label for="edge-threshold">Threshold</label>
<input type="range" id="edge-threshold" min="10" max="200" value="80">
</div>
<div class="control-group">
<label for="min-length">Min Length</label>
<input type="range" id="min-length" min="0" max="50" value="10">
</div>
<div class="control-group">
<label for="smoothness">Smoothness</label>
<input type="range" id="smoothness" min="0" max="3" step="0.1" value="1.0">
</div>
<div class="control-group" style="justify-content: center;">
<span class="stats-display">
<span id="line-count">0</span>
<div id="status-indicator" class="status-dot" title="Green: OK, Red: Limit Reached"></div>
</span>
</div>
</div>
<div class="buttons">
<button id="download-btn" disabled>Download SVG</button>
<button id="clear-btn" disabled>Clear</button>
</div>
</div>
</div>
<div id="drop-zone">
<div class="instruction">
Drag & Drop an Image Here<br>
<span style="font-size: 0.9rem">(or click to browse)</span>
</div>
<input type="file" id="file-input" accept="image/*" class="hidden">
<canvas id="output-canvas"></canvas>
</div>
<script>
const CANVAS_WIDTH = 1100;
const CANVAS_HEIGHT = 850;
let currentMode = 'concentrics';
let currentImage = null;
let vectorPaths = [];
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const canvas = document.getElementById('output-canvas');
const ctx = canvas.getContext('2d');
const tabs = document.querySelectorAll('.tab');
const globalControls = document.getElementById('global-controls');
const resolutionSlider = document.getElementById('resolution');
const hatchedControls = document.getElementById('hatched-controls');
const maxLinesSlider = document.getElementById('max-lines');
const angleOffsetSlider = document.getElementById('angle-offset');
const flowControls = document.getElementById('flow-controls');
const flowScaleSlider = document.getElementById('flow-scale');
const flowAlgoSelect = document.getElementById('flow-algo');
const densityControls = document.getElementById('density-controls');
const densityRadiusSlider = document.getElementById('density-radius');
const densityContrastSlider = document.getElementById('density-contrast');
const edgesControls = document.getElementById('edges-controls');
const edgeThresholdSlider = document.getElementById('edge-threshold');
const minLengthSlider = document.getElementById('min-length');
const smoothnessSlider = document.getElementById('smoothness');
const lineCountDisplay = document.getElementById('line-count');
const statusIndicator = document.getElementById('status-indicator');
const downloadBtn = document.getElementById('download-btn');
const clearBtn = document.getElementById('clear-btn');
const instruction = dropZone.querySelector('.instruction');
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
currentMode = tab.dataset.mode;
hatchedControls.classList.add('hidden');
edgesControls.classList.add('hidden');
flowControls.classList.add('hidden');
densityControls.classList.add('hidden');
globalControls.classList.remove('hidden');
if (currentMode === 'hatched') hatchedControls.classList.remove('hidden');
else if (currentMode === 'edges') {
edgesControls.classList.remove('hidden');
globalControls.classList.add('hidden');
} else if (currentMode === 'flow') {
flowControls.classList.remove('hidden');
} else if (currentMode === 'density') {
densityControls.classList.remove('hidden');
globalControls.classList.add('hidden');
}
if (currentImage) processImage();
});
});
resolutionSlider.addEventListener('input', () => { if (currentImage && currentMode !== 'edges' && currentMode !== 'density') processImage(); });
maxLinesSlider.addEventListener('input', () => { if (currentImage && currentMode === 'hatched') processImage(); });
angleOffsetSlider.addEventListener('input', () => { if (currentImage && currentMode === 'hatched') processImage(); });
flowScaleSlider.addEventListener('input', () => { if (currentImage && currentMode === 'flow') processImage(); });
flowAlgoSelect.addEventListener('change', () => { if (currentImage && currentMode === 'flow') processImage(); });
densityRadiusSlider.addEventListener('input', () => { if (currentImage && currentMode === 'density') processImage(); });
densityContrastSlider.addEventListener('input', () => { if (currentImage && currentMode === 'density') processImage(); });
edgeThresholdSlider.addEventListener('change', () => { if (currentImage && currentMode === 'edges') processImage(); });
minLengthSlider.addEventListener('change', () => { if (currentImage && currentMode === 'edges') processImage(); });
smoothnessSlider.addEventListener('change', () => { if (currentImage && currentMode === 'edges') processImage(); });
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('dragover'); });
dropZone.addEventListener('dragleave', () => { dropZone.classList.remove('dragover'); });
dropZone.addEventListener('drop', (e) => { e.preventDefault(); dropZone.classList.remove('dragover'); const file = e.dataTransfer.files[0]; if (file && file.type.startsWith('image/')) loadImage(file); });
dropZone.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', (e) => { if (e.target.files[0]) loadImage(e.target.files[0]); });
clearBtn.addEventListener('click', () => {
currentImage = null;
vectorPaths = [];
ctx.clearRect(0, 0, canvas.width, canvas.height);
instruction.classList.remove('hidden');
downloadBtn.disabled = true;
clearBtn.disabled = true;
fileInput.value = '';
lineCountDisplay.textContent = '0';
statusIndicator.className = 'status-dot';
});
downloadBtn.addEventListener('click', generateAndDownloadSVG);
function loadImage(file) {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
currentImage = img;
instruction.classList.add('hidden');
downloadBtn.disabled = false;
clearBtn.disabled = false;
processImage();
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
function processImage() {
if (!currentImage) return;
const offCanvas = document.createElement('canvas');
offCanvas.width = CANVAS_WIDTH; offCanvas.height = CANVAS_HEIGHT;
const offCtx = offCanvas.getContext('2d');
const scale = Math.max(CANVAS_WIDTH / currentImage.width, CANVAS_HEIGHT / currentImage.height);
const drawW = currentImage.width * scale; const drawH = currentImage.height * scale;
offCtx.fillStyle = '#FFFFFF'; offCtx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
offCtx.drawImage(currentImage, (CANVAS_WIDTH - drawW) / 2, (CANVAS_HEIGHT - drawH) / 2, drawW, drawH);
const imgData = offCtx.getImageData(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
ctx.fillStyle = '#FFFFFF'; ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
ctx.strokeStyle = '#000000'; ctx.lineWidth = 1; ctx.fillStyle = '#000000';
if (currentMode === 'edges') {
processEdgesMode(imgData);
} else if (currentMode === 'flow') {
processFlowMode(imgData);
} else if (currentMode === 'density') {
processDensityMode(imgData);
} else {
const sampleSize = parseInt(resolutionSlider.value, 10);
for (let y = 0; y < CANVAS_HEIGHT; y += sampleSize) {
for (let x = 0; x < CANVAS_WIDTH; x += sampleSize) {
const stats = getSampleStats(imgData, x, y, sampleSize, CANVAS_WIDTH, CANVAS_HEIGHT);
if (currentMode === 'concentrics') {
renderConcentric(ctx, x, y, sampleSize, stats.brightness);
} else if (currentMode === 'hatched') {
renderHatched(ctx, x, y, sampleSize, stats.brightness, stats.hue);
}
}
}
}
}
// --- FEATURE DENSITY MODE ---
function processDensityMode(imgData) {
const radius = parseInt(densityRadiusSlider.value, 10);
const contrast = parseInt(densityContrastSlider.value, 10);
const width = CANVAS_WIDTH;
const height = CANVAS_HEIGHT;
// 1. Get Grayscale
const gray = getGrayscaleData(imgData, width, height);
// 2. Calculate Mean (Low Pass) using fast separable blur
// Variance = (Pixel - Mean)^2. We use Abs diff for speed and similar visual effect.
const mean = fastBoxBlur(gray, width, height, radius);
// 3. Calculate Difference (High Pass components / Edges)
const diff = new Float32Array(width * height);
for(let i=0; i<width*height; i++) {
diff[i] = Math.abs(gray[i] - mean[i]);
}
// 4. Smooth the difference to create a "Field" or "Density Map"
// We blur the difference map so it becomes a region map rather than just thin lines
const density = fastBoxBlur(diff, width, height, radius);
// 5. Render to Canvas
const output = ctx.createImageData(width, height);
const outData = output.data;
for (let i = 0; i < width * height; i++) {
// Apply contrast scaling
let val = density[i] * contrast;
// Clamp
if (val > 255) val = 255;
if (val < 0) val = 0;
// Render Grayscale: High Variance = White (Bright), Low = Black
outData[i * 4] = val; // R
outData[i * 4 + 1] = val; // G
outData[i * 4 + 2] = val; // B
outData[i * 4 + 3] = 255; // Alpha
}
ctx.putImageData(output, 0, 0);
}
// Fast Separable Box Blur O(1) per pixel dependent on radius
function fastBoxBlur(source, w, h, r) {
const target = new Float32Array(w * h);
// Horizontal Pass
for (let y = 0; y < h; y++) {
let sum = 0;
// Pre-fill
for(let i=0; i<r; i++) sum += source[y*w];
for(let i=0; i<=r; i++) sum += source[y*w + i];
for (let x = 0; x < w; x++) {
target[y*w + x] = sum / (2*r+1);
let outgoing = x - r;
let incoming = x + r + 1;
let valOut = (outgoing < 0) ? source[y*w] : source[y*w + outgoing];
let valIn = (incoming >= w) ? source[y*w + w - 1] : source[y*w + incoming];
sum -= valOut;
sum += valIn;
}
}
// Vertical Pass (Read from target, Write to new buffer)
const output = new Float32Array(w * h);
for (let x = 0; x < w; x++) {
let sum = 0;
for(let i=0; i<r; i++) sum += target[x];
for(let i=0; i<=r; i++) sum += target[i*w + x];
for (let y = 0; y < h; y++) {
output[y*w + x] = sum / (2*r+1);
let outgoing = y - r;
let incoming = y + r + 1;
let valOut = (outgoing < 0) ? target[x] : target[outgoing*w + x];
let valIn = (incoming >= h) ? target[(h-1)*w + x] : target[incoming*w + x];
sum -= valOut;
sum += valIn;
}
}
return output;
}
// --- FLOW FIELD ---
function processFlowMode(imgData) {
const algo = flowAlgoSelect.value;
const gray = getGrayscaleData(imgData, CANVAS_WIDTH, CANVAS_HEIGHT);
if (algo === 'grid') {
renderFlowGrid(gray);
} else {
renderFlowDithered(gray);
}
}
function renderFlowGrid(gray) {
const width = CANVAS_WIDTH;
const height = CANVAS_HEIGHT;
const step = parseInt(resolutionSlider.value, 10);
const lineScale = parseFloat(flowScaleSlider.value);
ctx.beginPath();
for (let y = step; y < height - step; y += step) {
for (let x = step; x < width - step; x += step) {
const { angle, magnitude } = calculateStructureTensor(gray, x, y, width, step);
const len = (step * 0.8) * lineScale;
if (magnitude > 10) {
const cx = x + step/2, cy = y + step/2;
ctx.moveTo(cx - (Math.cos(angle) * len/2), cy - (Math.sin(angle) * len/2));
ctx.lineTo(cx + (Math.cos(angle) * len/2), cy + (Math.sin(angle) * len/2));
}
}
}
ctx.stroke();
}
function renderFlowDithered(gray) {
const width = CANVAS_WIDTH;
const height = CANVAS_HEIGHT;
const lineLen = parseInt(resolutionSlider.value, 10);
const contrast = parseFloat(flowScaleSlider.value);
const step = 4;
const errorBuffer = new Float32Array(width * height);
for(let i=0; i<gray.length; i++) {
errorBuffer[i] = (255 - gray[i]) * contrast;
}
ctx.beginPath();
for (let y = 0; y < height - step; y += step) {
for (let x = 0; x < width - step; x += step) {
const idx = y * width + x;
const oldVal = errorBuffer[idx];
const threshold = 128;
let error = 0;
if (oldVal > threshold) {
const { angle } = calculateStructureTensor(gray, x, y, width, 5);
const cx = x, cy = y;
ctx.moveTo(cx - (Math.cos(angle) * lineLen/2), cy - (Math.sin(angle) * lineLen/2));
ctx.lineTo(cx + (Math.cos(angle) * lineLen/2), cy + (Math.sin(angle) * lineLen/2));
error = oldVal - 255;
} else {
error = oldVal - 0;
}
if (x + step < width) errorBuffer[y * width + (x + step)] += error * 7/16;
if (x - step >= 0 && y + step < height) errorBuffer[(y + step) * width + (x - step)] += error * 3/16;
if (y + step < height) errorBuffer[(y + step) * width + x] += error * 5/16;
if (x + step < width && y + step < height) errorBuffer[(y + step) * width + (x + step)] += error * 1/16;
}
}
ctx.stroke();
}
function calculateStructureTensor(gray, x, y, width, windowSize) {
let sumE = 0;
let sumF = 0;
let weightSum = 0;
const half = Math.floor(windowSize / 2);
for (let wy = -half; wy <= half; wy++) {
for (let wx = -half; wx <= half; wx++) {
const iy = y + wy;
const ix = x + wx;
if(iy < 0 || iy >= CANVAS_HEIGHT || ix < 0 || ix >= CANVAS_WIDTH) continue;
const idx = iy * width + ix;
const gx = (gray[idx + 1] - gray[idx - 1]) || 0;
const gy = (gray[idx + width] - gray[idx - width]) || 0;
sumE += (gx * gx - gy * gy);
sumF += (2 * gx * gy);
weightSum++;
}
}
const angle = (0.5 * Math.atan2(sumF, sumE)) + (Math.PI / 2);
const magnitude = Math.sqrt(sumE*sumE + sumF*sumF) / (weightSum || 1);
return { angle, magnitude };
}
// --- OTHER HELPERS ---
function processEdgesMode(imgData) {
lineCountDisplay.textContent = "...";
statusIndicator.className = 'status-dot';
setTimeout(() => {
const threshold = parseInt(edgeThresholdSlider.value, 10);
const minLen = parseInt(minLengthSlider.value, 10);
const epsilon = parseFloat(smoothnessSlider.value);
const width = CANVAS_WIDTH, height = CANVAS_HEIGHT;
const grayPixels = getGrayscaleData(imgData, width, height);
const binaryPixels = applySobelAndThreshold(grayPixels, width, height, threshold);
const thinnedBinary = applyThinningBinary(binaryPixels, width, height);
const rawPaths = traceLines(thinnedBinary, width, height, minLen);
vectorPaths = (epsilon > 0) ? rawPaths.map(path => optimizePath(path, epsilon)) : rawPaths;
ctx.beginPath();
for (const path of vectorPaths) {
if (path.length === 0) continue;
ctx.moveTo(path[0].x, path[0].y);
for (let i = 1; i < path.length; i++) ctx.lineTo(path[i].x, path[i].y);
}
ctx.stroke();
lineCountDisplay.textContent = `${vectorPaths.length} Lines`;
statusIndicator.className = (vectorPaths.length > 5000) ? 'status-dot limit' : 'status-dot ok';
}, 10);
}
function traceLines(binaryPixels, w, h, minLen) {
const paths = []; const pixels = Uint8Array.from(binaryPixels);
const dx = [0, 1, 1, 1, 0, -1, -1, -1], dy = [-1, -1, 0, 1, 1, 1, 0, -1];
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
if (pixels[y*w+x] === 1) {
const path = []; let cx = x, cy = y, tracing = true;
while (tracing) {
path.push({x: cx, y: cy}); pixels[cy*w+cx] = 0; tracing = false;
for (let i = 0; i < 8; i++) {
const nx = cx + dx[i], ny = cy + dy[i];
if (nx >= 0 && nx < w && ny >= 0 && ny < h && pixels[ny*w+nx] === 1) {
cx = nx; cy = ny; tracing = true; break;
}
}
}
if (path.length >= minLen) paths.push(path);
}
}
}
return paths;
}
function optimizePath(points, epsilon) {
if (points.length < 3) return points;
let maxDist = 0, index = 0;
const start = points[0], end = points[points.length - 1];
for (let i = 1; i < points.length - 1; i++) {
const d = perpendicularDistance(points[i], start, end);
if (d > maxDist) { maxDist = d; index = i; }
}
return (maxDist > epsilon)
? optimizePath(points.slice(0, index + 1), epsilon).slice(0, -1).concat(optimizePath(points.slice(index), epsilon))
: [start, end];
}
function perpendicularDistance(point, lineStart, lineEnd) {
let dx = lineEnd.x - lineStart.x, dy = lineEnd.y - lineStart.y;
if (dx === 0 && dy === 0) return Math.hypot(point.x - lineStart.x, point.y - lineStart.y);
return Math.abs(dy * point.x - dx * point.y + lineEnd.x * lineStart.y - lineEnd.y * lineStart.x) / Math.sqrt(dx * dx + dy * dy);
}
function getGrayscaleData(imgData, w, h) {
const gray = new Uint8Array(w * h); const data = imgData.data;
for (let i = 0; i < w * h; i++) gray[i] = 0.299 * data[i * 4] + 0.587 * data[i * 4 + 1] + 0.114 * data[i * 4 + 2];
return gray;
}
function applySobelAndThreshold(gray, w, h, threshold) {
const binary = new Uint8Array(w * h);
const gx = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], gy = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]];
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
let sumX = 0, sumY = 0;
for (let i = -1; i <= 1; i++) for (let j = -1; j <= 1; j++) {
const val = gray[(y + i) * w + (x + j)];
sumX += gx[i + 1][j + 1] * val; sumY += gy[i + 1][j + 1] * val;
}
binary[y * w + x] = Math.sqrt(sumX * sumX + sumY * sumY) > threshold ? 1 : 0;
}
}
return binary;
}
function applyThinningBinary(binary, w, h) {
let pixels = Uint8Array.from(binary), framing = new Uint8Array(w * h), changed = true;
const get = (arr, x, y) => (x >= 0 && x < w && y >= 0 && y < h) ? arr[y * w + x] : 0;
while (changed) {
changed = false; framing.set(pixels);
for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
if (pixels[y * w + x] === 0) continue;
const p2=get(pixels,x,y-1), p3=get(pixels,x+1,y-1), p4=get(pixels,x+1,y), p5=get(pixels,x+1,y+1);
const p6=get(pixels,x,y+1), p7=get(pixels,x-1,y+1), p8=get(pixels,x-1,y), p9=get(pixels,x-1,y-1);
const A = (p2==0&&p3==1)+(p3==0&&p4==1)+(p4==0&&p5==1)+(p5==0&&p6==1)+(p6==0&&p7==1)+(p7==0&&p8==1)+(p8==0&&p9==1)+(p9==0&&p2==1);
const B = p2+p3+p4+p5+p6+p7+p8+p9;
if (A===1 && B>=2 && B<=6 && p2*p4*p6===0 && p4*p6*p8===0) { framing[y*w+x]=0; changed=true; }
}
pixels.set(framing);
for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
if (pixels[y * w + x] === 0) continue;
const p2=get(pixels,x,y-1), p3=get(pixels,x+1,y-1), p4=get(pixels,x+1,y), p5=get(pixels,x+1,y+1);
const p6=get(pixels,x,y+1), p7=get(pixels,x-1,y+1), p8=get(pixels,x-1,y), p9=get(pixels,x-1,y-1);
const A = (p2==0&&p3==1)+(p3==0&&p4==1)+(p4==0&&p5==1)+(p5==0&&p6==1)+(p6==0&&p7==1)+(p7==0&&p8==1)+(p8==0&&p9==1)+(p9==0&&p2==1);
const B = p2+p3+p4+p5+p6+p7+p8+p9;
if (A===1 && B>=2 && B<=6 && p2*p4*p8===0 && p2*p6*p8===0) { framing[y*w+x]=0; changed=true; }
}
pixels.set(framing);
}
return pixels;
}
function getSampleStats(imgData, startX, startY, sampleSize, width, height) {
let rSum = 0, gSum = 0, bSum = 0, count = 0; const data = imgData.data;
for (let y = startY; y < startY + sampleSize && y < height; y++) for (let x = startX; x < startX + sampleSize && x < width; x++) {
const i = (y * width + x) * 4; rSum += data[i]; gSum += data[i + 1]; bSum += data[i + 2]; count++;
}
if (count === 0) return { brightness: 255, hue: 0 };
const r = Math.round(rSum/count), g = Math.round(gSum/count), b = Math.round(bSum/count);
return { brightness: 0.299 * r + 0.587 * g + 0.114 * b, hue: rgbToHue(r, g, b) };
}
function rgbToHue(r, g, b) {
r/=255; g/=255; b/=255; const max=Math.max(r,g,b), min=Math.min(r,g,b); let h=0;
if(max!==min){ const d=max-min; h=max===r?(g-b)/d+(g<b?6:0):max===g?(b-r)/d+2:(r-g)/d+4; h/=6; }
return h * 360;
}
function renderConcentric(ctx, x, y, size, brightness) {
const numCircles = Math.round((1 - (brightness/255)) * 5);
if (numCircles > 0) {
const cx=x+size/2, cy=y+size/2, step=((size/2)*0.9)/5;
ctx.beginPath(); for(let i=0; i<numCircles; i++) ctx.arc(cx, cy, step*(5-i), 0, Math.PI*2); ctx.stroke();
}
}
function renderHatched(ctx, x, y, size, brightness, hue) {
const MAX_LINES=parseInt(maxLinesSlider.value, 10), angleOffset=parseInt(angleOffsetSlider.value, 10);
let numLines = Math.floor( (1 - (brightness/255)) * (MAX_LINES-1) ) + 1;
const cx=x+size/2, cy=y+size/2;
ctx.save(); ctx.beginPath(); ctx.rect(x,y,size,size); ctx.clip();
ctx.translate(cx,cy); ctx.rotate((hue+angleOffset)*Math.PI/180);
const spacing=(size*0.9)/(numLines+1), lineLen=size*1.5;
ctx.beginPath(); for(let i=0; i<numLines; i++) {
const yOffset=(i-(numLines-1)/2)*spacing; ctx.moveTo(-lineLen/2, yOffset); ctx.lineTo(lineLen/2, yOffset);
}
ctx.stroke(); ctx.restore();
}
function generateAndDownloadSVG() {
if (!currentImage) return;
// Basic implementation supports download for Concentrics, Hatched, and Flow.
// Feature Density mode renders raster data which is not converted to vector SVG here.
if (currentMode === 'density') {
alert("Feature Density mode displays a raster field and does not export to SVG in this version.");
return;
}
let svgContent = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${CANVAS_WIDTH} ${CANVAS_HEIGHT}" width="11in" height="8.5in"><rect width="100%" height="100%" fill="white"/>`;
if (currentMode === 'edges') {
for (const path of vectorPaths) {
if (path.length < 2) continue;
const pointsStr = path.map(p => `${p.x},${p.y}`).join(' ');
svgContent += `<polyline points="${pointsStr}" fill="none" stroke="black" stroke-width="1" />`;
}
} else if (currentMode === 'flow') {
const algo = flowAlgoSelect.value;
const step = (algo === 'grid') ? parseInt(resolutionSlider.value, 10) : 4;
const lineLenParam = parseInt(resolutionSlider.value, 10);
const lineScale = parseFloat(flowScaleSlider.value);
const offCanvas = document.createElement('canvas'); offCanvas.width = CANVAS_WIDTH; offCanvas.height = CANVAS_HEIGHT;
const offCtx = offCanvas.getContext('2d');
const scale = Math.max(CANVAS_WIDTH/currentImage.width, CANVAS_HEIGHT/currentImage.height);
const drawW = currentImage.width * scale; const drawH = currentImage.height * scale;
offCtx.fillStyle = '#FFFFFF'; offCtx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
offCtx.drawImage(currentImage, (CANVAS_WIDTH - drawW)/2, (CANVAS_HEIGHT - drawH)/2, drawW, drawH);
const gray = getGrayscaleData(offCtx.getImageData(0,0,CANVAS_WIDTH,CANVAS_HEIGHT), CANVAS_WIDTH, CANVAS_HEIGHT);
if (algo === 'grid') {
for (let y = step; y < CANVAS_HEIGHT - step; y += step) {
for (let x = step; x < CANVAS_WIDTH - step; x += step) {
const { angle, magnitude } = calculateStructureTensor(gray, x, y, CANVAS_WIDTH, step);
const len = (step * 0.8) * lineScale;
if (magnitude > 10) {
const cx = x + step/2, cy = y + step/2;
const x1 = cx - Math.cos(angle)*len/2, y1 = cy - Math.sin(angle)*len/2;
const x2 = cx + Math.cos(angle)*len/2, y2 = cy + Math.sin(angle)*len/2;
svgContent += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="black" stroke-width="1"/>`;
}
}
}
} else {
// Dithering SVG
const errorBuffer = new Float32Array(CANVAS_WIDTH * CANVAS_HEIGHT);
for(let i=0; i<gray.length; i++) errorBuffer[i] = (255 - gray[i]) * lineScale;
for (let y = 0; y < CANVAS_HEIGHT - step; y += step) {
for (let x = 0; x < CANVAS_WIDTH - step; x += step) {
const idx = y * CANVAS_WIDTH + x;
const oldVal = errorBuffer[idx];
let error = 0;
if (oldVal > 128) {
const { angle } = calculateStructureTensor(gray, x, y, CANVAS_WIDTH, 5);
const len = lineLenParam;
const x1 = x - Math.cos(angle)*len/2, y1 = y - Math.sin(angle)*len/2;
const x2 = x + Math.cos(angle)*len/2, y2 = y + Math.sin(angle)*len/2;
svgContent += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="black" stroke-width="1"/>`;
error = oldVal - 255;
} else {
error = oldVal - 0;
}
if (x + step < CANVAS_WIDTH) errorBuffer[y * CANVAS_WIDTH + (x + step)] += error * 7/16;
if (x - step >= 0 && y + step < CANVAS_HEIGHT) errorBuffer[(y + step) * CANVAS_WIDTH + (x - step)] += error * 3/16;
if (y + step < CANVAS_HEIGHT) errorBuffer[(y + step) * CANVAS_WIDTH + x] += error * 5/16;
if (x + step < CANVAS_WIDTH && y + step < CANVAS_HEIGHT) errorBuffer[(y + step) * CANVAS_WIDTH + (x + step)] += error * 1/16;
}
}
}
} else {
const sampleSize = parseInt(resolutionSlider.value, 10);
const offCanvas = document.createElement('canvas'); offCanvas.width = CANVAS_WIDTH; offCanvas.height = CANVAS_HEIGHT;
const offCtx = offCanvas.getContext('2d');
const scale = Math.max(CANVAS_WIDTH / currentImage.width, CANVAS_HEIGHT / currentImage.height);
const drawW = currentImage.width * scale; const drawH = currentImage.height * scale;
offCtx.fillStyle = '#FFFFFF'; offCtx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
offCtx.drawImage(currentImage, (CANVAS_WIDTH - drawW)/2, (CANVAS_HEIGHT - drawH)/2, drawW, drawH);
const imgData = offCtx.getImageData(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
for (let y = 0; y < CANVAS_HEIGHT; y += sampleSize) {
for (let x = 0; x < CANVAS_WIDTH; x += sampleSize) {
const stats = getSampleStats(imgData, x, y, sampleSize, CANVAS_WIDTH, CANVAS_HEIGHT);
const cx = x + sampleSize / 2, cy = y + sampleSize / 2;
if (currentMode === 'concentrics') {
const numCircles = Math.round((1 - (stats.brightness / 255)) * 5);
if (numCircles > 0) {
const step = ((sampleSize / 2) * 0.9) / 5;
for (let i = 0; i < numCircles; i++) svgContent += `<circle cx="${cx}" cy="${cy}" r="${step * (5 - i)}" fill="none" stroke="black" stroke-width="1" />`;
}
} else if (currentMode === 'hatched') {
const maxLines = parseInt(maxLinesSlider.value, 10);
const angleOffset = parseInt(angleOffsetSlider.value, 10);
let numLines = Math.floor( (1 - (stats.brightness / 255)) * (maxLines - 1) ) + 1;
const spacing = (sampleSize * 0.9) / (numLines + 1);
svgContent += `<g transform="translate(${cx}, ${cy}) rotate(${stats.hue + angleOffset})">`;
for (let i = 0; i < numLines; i++) {
const yOffset = (i - (numLines - 1) / 2) * spacing;
svgContent += `<line x1="${-sampleSize/2}" y1="${yOffset}" x2="${sampleSize/2}" y2="${yOffset}" stroke="black" stroke-width="1" />`;
}
svgContent += `</g>`;
}
}
}
}
svgContent += `</svg>`;
const blob = new Blob([svgContent], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a'); link.href = url; link.download = `vector-${currentMode}.svg`;
document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url);
}
</script>
</body>
</html>