-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
367 lines (310 loc) · 12.2 KB
/
Copy pathscript.js
File metadata and controls
367 lines (310 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
class GraphVisualizer {
constructor() {
this.canvas = document.getElementById('canvas');
this.ctx = this.canvas.getContext('2d');
this.vertices = [];
this.edges = [];
this.isDragging = false;
this.dragOffset = { x: 0, y: 0 };
this.pan = { x: 0, y: 0 };
this.zoom = 1;
this.selectedVertex = null;
this.setupCanvas();
this.setupEventListeners();
}
setupCanvas() {
const container = this.canvas.parentElement;
const resizeCanvas = () => {
const rect = container.getBoundingClientRect();
this.canvas.width = rect.width - 40;
this.canvas.height = rect.height - 80;
this.draw();
};
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
}
setupEventListeners() {
this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this));
this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this));
this.canvas.addEventListener('mouseup', this.handleMouseUp.bind(this));
this.canvas.addEventListener('wheel', this.handleWheel.bind(this));
this.canvas.addEventListener('click', this.handleClick.bind(this));
document.getElementById('input-type').addEventListener('change', this.updateFormatHelp.bind(this));
}
updateFormatHelp() {
const inputType = document.getElementById('input-type').value;
const helpDiv = document.getElementById('format-help');
if (inputType === 'adjacency') {
helpDiv.innerHTML = `
<div class="format-title">Adjacency List Format:</div>
<div>Each line: vertex: neighbor1,neighbor2,...</div>
<div class="format-example">0: 1,2<br>1: 0,3<br>2: 0,3<br>3: 1,2</div>
`;
} else {
helpDiv.innerHTML = `
<div class="format-title">Edge List Format:</div>
<div>Each line: vertex1,vertex2 or vertex1 vertex2</div>
<div class="format-example">0,1<br>0,2<br>1,3<br>2,3</div>
`;
}
}
parseInput(input, type, numVertices, isDirected) {
this.vertices = [];
this.edges = [];
// Initialize vertices
for (let i = 0; i < numVertices; i++) {
this.vertices.push({
id: i,
x: Math.random() * (this.canvas.width - 200) + 100,
y: Math.random() * (this.canvas.height - 200) + 100,
radius: 25
});
}
const lines = input.trim().split('\n').filter(line => line.trim());
if (type === 'adjacency') {
lines.forEach(line => {
const [vertex, neighbors] = line.split(':').map(s => s.trim());
if (neighbors) {
const neighborList = neighbors.split(',').map(n => parseInt(n.trim()));
neighborList.forEach(neighbor => {
if (!isNaN(neighbor) && neighbor < numVertices) {
if (!this.edgeExists(parseInt(vertex), neighbor)) {
this.edges.push({
from: parseInt(vertex),
to: neighbor,
directed: isDirected
});
}
}
});
}
});
} else if (type === 'edge') {
lines.forEach(line => {
const edge = line.split(/[,\s]+/).map(v => parseInt(v.trim()));
if (edge.length === 2 && !isNaN(edge[0]) && !isNaN(edge[1]) &&
edge[0] < numVertices && edge[1] < numVertices) {
if (!this.edgeExists(edge[0], edge[1])) {
this.edges.push({
from: edge[0],
to: edge[1],
directed: isDirected
});
}
}
});
}
}
edgeExists(from, to) {
return this.edges.some(edge =>
(edge.from === from && edge.to === to) ||
(!edge.directed && edge.from === to && edge.to === from)
);
}
draw() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.save();
// Apply transformations
this.ctx.translate(this.pan.x, this.pan.y);
this.ctx.scale(this.zoom, this.zoom);
// Draw edges
this.edges.forEach(edge => this.drawEdge(edge));
// Draw vertices
this.vertices.forEach(vertex => this.drawVertex(vertex));
this.ctx.restore();
}
drawVertex(vertex) {
const isSelected = this.selectedVertex === vertex.id;
// Draw vertex circle
this.ctx.beginPath();
this.ctx.arc(vertex.x, vertex.y, vertex.radius, 0, 2 * Math.PI);
this.ctx.fillStyle = isSelected ? '#ff6b6b' : '#667eea';
this.ctx.fill();
this.ctx.strokeStyle = isSelected ? '#ff5252' : '#5a67d8';
this.ctx.lineWidth = 3;
this.ctx.stroke();
// Draw vertex label
this.ctx.fillStyle = 'white';
this.ctx.font = 'bold 16px Arial';
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
this.ctx.fillText(vertex.id.toString(), vertex.x, vertex.y);
}
drawEdge(edge) {
const fromVertex = this.vertices[edge.from];
const toVertex = this.vertices[edge.to];
if (!fromVertex || !toVertex) return;
const dx = toVertex.x - fromVertex.x;
const dy = toVertex.y - fromVertex.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// Calculate edge endpoints (on circle boundary)
const fromX = fromVertex.x + (dx / distance) * fromVertex.radius;
const fromY = fromVertex.y + (dy / distance) * fromVertex.radius;
const toX = toVertex.x - (dx / distance) * toVertex.radius;
const toY = toVertex.y - (dy / distance) * toVertex.radius;
// Draw edge line
this.ctx.beginPath();
this.ctx.moveTo(fromX, fromY);
this.ctx.lineTo(toX, toY);
this.ctx.strokeStyle = '#666';
this.ctx.lineWidth = 2;
this.ctx.stroke();
// Draw arrow for directed graphs
if (edge.directed) {
this.drawArrow(fromX, fromY, toX, toY);
}
// Draw edge weight if needed
const midX = (fromX + toX) / 2;
const midY = (fromY + toY) / 2;
// Optional: draw edge weight
// this.ctx.fillStyle = '#333';
// this.ctx.font = '12px Arial';
// this.ctx.textAlign = 'center';
// this.ctx.fillText('1', midX, midY - 10);
}
drawArrow(fromX, fromY, toX, toY) {
const angle = Math.atan2(toY - fromY, toX - fromX);
const arrowLength = 15;
const arrowAngle = Math.PI / 6;
this.ctx.beginPath();
this.ctx.moveTo(toX, toY);
this.ctx.lineTo(
toX - arrowLength * Math.cos(angle - arrowAngle),
toY - arrowLength * Math.sin(angle - arrowAngle)
);
this.ctx.moveTo(toX, toY);
this.ctx.lineTo(
toX - arrowLength * Math.cos(angle + arrowAngle),
toY - arrowLength * Math.sin(angle + arrowAngle)
);
this.ctx.strokeStyle = '#666';
this.ctx.lineWidth = 2;
this.ctx.stroke();
}
handleMouseDown(e) {
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
this.isDragging = true;
this.dragOffset = { x: x - this.pan.x, y: y - this.pan.y };
}
handleMouseMove(e) {
if (!this.isDragging) return;
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
this.pan.x = x - this.dragOffset.x;
this.pan.y = y - this.dragOffset.y;
this.draw();
}
handleMouseUp() {
this.isDragging = false;
}
handleWheel(e) {
e.preventDefault();
const zoomFactor = 0.1;
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const zoom = e.deltaY > 0 ? -zoomFactor : zoomFactor;
const newZoom = Math.max(0.1, Math.min(3, this.zoom + zoom));
// Zoom towards mouse position
this.pan.x -= (x - this.pan.x) * (newZoom / this.zoom - 1);
this.pan.y -= (y - this.pan.y) * (newZoom / this.zoom - 1);
this.zoom = newZoom;
this.draw();
}
handleClick(e) {
const rect = this.canvas.getBoundingClientRect();
const x = (e.clientX - rect.left - this.pan.x) / this.zoom;
const y = (e.clientY - rect.top - this.pan.y) / this.zoom;
this.selectedVertex = null;
this.vertices.forEach(vertex => {
const dx = x - vertex.x;
const dy = y - vertex.y;
if (dx * dx + dy * dy <= vertex.radius * vertex.radius) {
this.selectedVertex = vertex.id;
}
});
this.draw();
}
generateRandomGraph(numVertices, isDirected) {
const edges = [];
const density = 0.3; // 30% chance for each edge
for (let i = 0; i < numVertices; i++) {
for (let j = isDirected ? 0 : i + 1; j < numVertices; j++) {
if (i !== j && Math.random() < density) {
edges.push(`${i},${j}`);
}
}
}
return edges.join('\n');
}
clear() {
this.vertices = [];
this.edges = [];
this.selectedVertex = null;
this.pan = { x: 0, y: 0 };
this.zoom = 1;
this.draw();
}
}
const visualizer = new GraphVisualizer();
function showError(message) {
const errorDiv = document.getElementById('error-message');
errorDiv.innerHTML = `<div class="error">${message}</div>`;
setTimeout(() => errorDiv.innerHTML = '', 5000);
}
function visualizeGraph() {
const numVertices = parseInt(document.getElementById('vertices').value);
const inputType = document.getElementById('input-type').value;
const graphInput = document.getElementById('graph-input').value;
const isDirected = document.getElementById('directed').checked;
if (!numVertices || numVertices < 1) {
showError('Please enter a valid number of vertices (at least 1)');
return;
}
if (!graphInput.trim()) {
showError('Please enter graph data');
return;
}
try {
visualizer.parseInput(graphInput, inputType, numVertices, isDirected);
visualizer.draw();
document.getElementById('error-message').innerHTML = '';
} catch (error) {
showError('Error parsing graph input. Please check your format and try again.');
}
}
function generateRandom() {
const numVertices = parseInt(document.getElementById('vertices').value) || 5;
const isDirected = document.getElementById('directed').checked;
const inputType = document.getElementById('input-type').value;
if (inputType === 'edge') {
const randomGraph = visualizer.generateRandomGraph(numVertices, isDirected);
document.getElementById('graph-input').value = randomGraph;
} else {
// Generate adjacency list format
const adjacencyList = [];
for (let i = 0; i < numVertices; i++) {
const neighbors = [];
for (let j = 0; j < numVertices; j++) {
if (i !== j && Math.random() < 0.3) {
neighbors.push(j);
}
}
if (neighbors.length > 0) {
adjacencyList.push(`${i}: ${neighbors.join(',')}`);
}
}
document.getElementById('graph-input').value = adjacencyList.join('\n');
}
visualizeGraph();
}
function clearCanvas() {
visualizer.clear();
document.getElementById('graph-input').value = '';
document.getElementById('error-message').innerHTML = '';
}
// Initialize with example
visualizeGraph();