-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrapher.js
939 lines (807 loc) · 27.3 KB
/
grapher.js
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
/*
Grapher (JavaScript tool for drawing graphs)
Version: 1.0
Description: I created this tool because I wanted to more easily
draw graphs especially for use in LaTeX editors. Using the graphing
and/or picture packages provided works, but they aren't exactly
very easy to use, since I needed to type LaTeX code to draw circles and lines manually.
This tool is useful for anyone needing to draw graphs, especially
if they need to be typeset (such as in an academic paper or homework).
You can easily implement this using an HTML5 canvas of a reasonable size. You also need an
output textbox (for LaTeX code), and buttons for saving as PNG and saving as LaTeX.
-------------------------------------------------------------------
Directions:
Double click to create vertices
Single click to select vertices and edges
While a vertex or edge is selected:
- Delete key deletes the vertex or edge
- Typing adds text to the vertex or edge, backspace works as expected
- To make subscripted numbers, type an underscore followed by
numbers and then another underscore. Example: _3_
Note that these will be automatically converted to the correct
braces for LaTeX code.
While a vertex is selected:
- Moving the mouse moves the vertex
- Pressing shift then dragging will create an undirected edge
- Pressing control then dragging will create a directed edge
*/
// Constants. Note these are not const because they aren't cross-browser compatible
var VERTEX_RADIUS = 30; // Size of vertices
var VERTEX_PADDING = 10; // Distance between text and circle edge
var FONT_SIZE = 24; // Default font size
var FONT = 'Cambria'; // Cambria: works well for subscripted numbers
var SNAP_MARGIN = 10; // Snap-to distance (how close should a vertex be before it snaps to another vertex's x or y coordinate)
var EDGE_MARGIN = 6; // Selection margin for an edge (how close to an edge the mouse has to be for it to be selected)
// Keycode constants
var BACKSPACE = 8;
var SHIFT = 16;
var CTRL = 17;
var DELETE = 46;
// Canvas element
var canvas = null;
// Keep track of objects on the canvas
var selectedObject = null; // Mouse selected object
var currentEdge = null; // For storing a temporary edge
var sourceMouse = null; // Keep track of original mouse position, for moving objects
var movingObject = false; // Keep track of whether we are moving an object (vertex/edge)
var vertices = []; // Array to store vertices
var edges = []; // Array to store edges
var font = null; // Font type
// Boolean variables to keep track of what keys/mouse have been pressed
var lastKey = null;
var shift = false;
var ctrl = false;
var mouseDown = false;
// Initialize our event listeners and other functions when the window has loaded
window.onload = function()
{
// Set our canvas (named canvas in the html file)
canvas = document.getElementById('canvas');
canvas.onselectstart = function () // Prevents selecting text outside canvas
{
return false;
}
c = canvas.getContext('2d'); // Two-dimensional drawing context
// Mouse press event
canvas.onmousedown = function(e)
{
// Get the mouse coordinates
var mouse = crossBrowserRelativeMousePos(e);
sourceMouse = mouse;
selectedObject = selectObject(mouse.x, mouse.y); // If our mouse click is in some vertex/edge, select it
if (selectedObject != null)
{
if (selectedObject instanceof Vertex)
{
if (shift && currentEdge == null) // If shift is held, we can connect an edge from a vertex
{
currentEdge = new TempEdge(selectedObject, mouse);
}
else if (ctrl && currentEdge == null) // If control is held, we can connect a directed edge from a vertex
{
currentEdge = new TempDirEdge(selectedObject, mouse);
}
else // Otherwise, we are moving an object (vertex or edge)
{
movingObject = true;
if (selectedObject.setStartPoint) // Keep track of the original start point of vertex
{
selectedObject.setStartPoint(mouse.x, mouse.y);
}
}
}
}
mouseDown = true;
};
// Mouse release event
canvas.onmouseup = function(e)
{
// Get the mouse coordinates
var mouse = crossBrowserRelativeMousePos(e);
movingObject = false;
if (currentEdge instanceof TempEdge || currentEdge instanceof TempDirEdge) // If edge isn't connected to anywhere, then we remove it
{
currentEdge = null;
}
else if (currentEdge instanceof Edge || currentEdge instanceof DirEdge) // If it has been connected to another vertex, add it to edge array
{
if (!containsEdge(currentEdge))
{
edges.push(currentEdge);
}
// Reset the current edge and last key pressed
currentEdge = null;
lastKey = null;
}
mouseDown = false;
};
// Mouse move event
canvas.onmousemove = function(e)
{
// Get the mouse position
var mouse = crossBrowserRelativeMousePos(e);
if (currentEdge != null) // If we are currently creating an edge
{
var destVertex = selectObject(mouse.x, mouse.y); // Select an object that the mouse clicked on
if (selectedObject != null)
{
if (destVertex instanceof Vertex == false) // if destVertex is not a vertex, we don't care
{
destVertex = null;
}
if (currentEdge != null && selectedObject instanceof Vertex) // If we are creating an edge, do something with it
{
if (destVertex == null) // Move our temp edge/directed edge to the current mouse position
{
if (lastKey == SHIFT)
{
currentEdge = new TempEdge(selectedObject, mouse);
}
else if (lastKey == CTRL)
{
currentEdge = new TempDirEdge(selectedObject, mouse);
}
}
else // If the destVertex is some other vertex, make an edge between both vertices
{
if (lastKey == SHIFT)
{
currentEdge = new Edge(selectedObject, destVertex);
}
else if (lastKey == CTRL)
{
currentEdge = new DirEdge(selectedObject, destVertex);
}
}
}
}
}
if (movingObject) // If an object is moving, then move it
{
selectedObject.setAnchorPoint(mouse.x, mouse.y); // Set the position to wherever the mouse is
snap(selectedObject); // Snap to alignment (with other vertices)
}
draw();
};
canvas.ondblclick = function(e)
{
// Get the mouse coordinates
var mouse = crossBrowserRelativeMousePos(e);
selectedObject = selectObject(mouse.x, mouse.y);
if (selectedObject == null) // If there is nothing at the mouse position, create a new vertex
{
selectedObject = new Vertex(mouse.x, mouse.y);
vertices.push(selectedObject);
draw();
}
};
}
// Key down event
document.onkeydown = function(e)
{
var key = crossBrowserKey(e);
// We don't want to be able to change between directed/undirected edges while mouse is being pressed
if (!mouseDown)
{
lastKey = key;
}
// Check what keys have been pressed
if (key == SHIFT)
{
shift = true;
}
else if (key == CTRL)
{
ctrl = true;
}
else if (selectedObject != null)
{
if (key == BACKSPACE) // Delete text from the vertex or edge
{
selectedObject.text = selectedObject.text.substr(0 , selectedObject.text.length - 1);
draw();
return false;
}
else if (key == DELETE) // Delete the vertex or edge selected
{
for (var i = 0, n = vertices.length; i < n; i++) // Delete vertex selected
{
if (vertices[i] == selectedObject)
{
vertices.splice(i--, 1);
}
}
for (var i = 0, n = edges.length; i < n; i++) // Delete edge selected, or edges incident on deleted vertex
{
if (edges[i] == selectedObject || edges[i].v1 == selectedObject || edges[i].v2 == selectedObject)
{
edges.splice(i--, 1);
}
}
selectedObject = null;
draw();
}
}
if (key == BACKSPACE) // Prevent browser back function
{
return false;
}
}
// Key up event
document.onkeyup = function(e)
{
var key = crossBrowserKey(e);
if (key == SHIFT)
{
shift = false;
}
else if (key == CTRL)
{
ctrl = false;
}
}
// Key press event
document.onkeypress = function(e)
{
var key = crossBrowserKey(e);
if (!canvasHasFocus)
{
return true;
}
else if (selectedObject != null && key >= 0x20 && key <= 0x7E) // A valid alphanumeric + symbols key
{
if (key >= 48 && key <= 57)
{
selectedObject.text += String.fromCharCode(key);
}
else
{
selectedObject.text += String.fromCharCode(key);
}
draw();
return false;
}
else if (key == BACKSPACE) // Prevent browser back function
{
return false;
}
}
// Attempt to select an object at the given (x, y) out of our added vertices and edges
function selectObject(x, y)
{
for (var i = 0, n = vertices.length; i < n; i++)
{
if (vertices[i].contains(x, y))
{
return vertices[i];
}
}
for (var i = 0, n = edges.length; i < n; i++)
{
if (edges[i].contains(x, y))
{
return edges[i];
}
}
}
// Snap a vertex (for aligning with other vertices)
function snap(vertex)
{
for (var i = 0, n = vertices.length; i < n; i++)
{
if (Math.abs(vertex.x - vertices[i].x) < SNAP_MARGIN)
vertex.x = vertices[i].x;
if (Math.abs(vertex.y - vertices[i].y) < SNAP_MARGIN)
vertex.y = vertices[i].y;
}
}
// Draw based on the 2D context
function draw()
{
c = canvas.getContext('2d');
drawWith(c);
}
// Draw with a certain context (either 2D, LaTeX, etc)
function drawWith(c)
{
// Clear the rectangle
c.clearRect(0, 0, canvas.width, canvas.height);
// Draw each vertex
for (var i = 0, n = vertices.length; i < n; i++)
{
c.fillStyle = c.strokeStyle = (vertices[i] == selectedObject) ? 'green' : 'black';
vertices[i].draw(c);
}
// Draw each edge
for (var i = 0, n = edges.length; i < n; i++)
{
c.fillStyle = c.strokeStyle = (edges[i] == selectedObject) ? 'green' : 'black';
edges[i].draw(c);
}
// If there is an edge being created, draw that
if (currentEdge != null)
{
currentEdge.draw(c);
}
}
// Draw text using the cambria font
function drawText(c, oldText, x, y, angle, isSelected)
{
var text = makeSubscripts(oldText);
c.font = FONT_SIZE + 'px ' + FONT + ', serif';
var width = c.measureText(text).width;
x -= width/2;
// For placing text so it does not overlap with an edge (when it is being rotated)
if (angle != null)
{
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var cornerPointX = (width / 2 + 5) * (cos > 0 ? 1 : -1);
var cornerPointY = (10 + 5) * (sin > 0 ? 1 : -1);
var slide = sin * Math.pow(Math.abs(sin), 40) * cornerPointX - cos * Math.pow(Math.abs(cos), 10) * cornerPointY;
x += cornerPointX - sin * slide;
y -= cornerPointY + cos * slide;
}
x = Math.round(x);
y = Math.round(y);
if ('advancedFillText' in c)
{
c.advancedFillText(text, oldText, x + width / 2, y, angle);
}
else
{
c.fillText(text, x, y + 6);
}
}
// Draw the arrow head
function drawArrow(c, x, y, angle) {
var dx = Math.cos(angle);
var dy = Math.sin(angle);
c.beginPath();
c.moveTo(x, y);
c.lineTo(x - 8 * dx + 5 * dy, y - 8 * dy - 5 * dx);
c.lineTo(x - 8 * dx - 5 * dy, y - 8 * dy + 5 * dx);
c.fill();
c.stroke();
}
// Prevents duplicate edges by checking if an edge has already been added
// This also means that an undirected edge must be deleted before directed edges can be added and vice versa
function containsEdge(edge)
{
for (var i = 0, n = edges.length; i < n; i++)
{
if (edge.v1 == edges[i].v1 && edge.v2 == edges[i].v2 || edge.v2 == edges[i].v1 && edge.v1 == edges[i].v2)
{
return true;
}
}
return false;
}
// Functions for getting the mouse position or key codes across multiple browsers
function crossBrowserKey(e) {
e = e || window.event;
return e.which || e.keyCode;
}
function crossBrowserElementPos(e) {
e = e || window.event;
var obj = e.target || e.srcElement;
var x = 0, y = 0;
while(obj.offsetParent) {
x += obj.offsetLeft;
y += obj.offsetTop;
obj = obj.offsetParent;
}
return { 'x': x, 'y': y };
}
function crossBrowserMousePos(e) {
e = e || window.event;
return {
'x': e.pageX || e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft,
'y': e.pageY || e.clientY + document.body.scrollTop + document.documentElement.scrollTop
};
}
function crossBrowserRelativeMousePos(e) {
var element = crossBrowserElementPos(e);
var mouse = crossBrowserMousePos(e);
return {
'x': mouse.x - element.x,
'y': mouse.y - element.y
};
}
function crossBrowserKey(e) {
e = e || window.event;
return e.which || e.keyCode;
}
function canvasHasFocus() {
return (document.activeElement || document.body) == document.body;
}
// Exporting functions
function toPNG()
{
var oldSelectedObject = selectedObject;
selectedObject = null;
drawUsing(canvas.getContext('2d'));
selectedObject = oldSelectedObject;
var pngData = canvas.toDataURL('image/png');
document.location.href = pngData;
}
// An object to help draw to LaTeX, i.e. convert to LaTeX code (via TikZ picture)
// Contains the same functions as the normal context drawing, except this writes code
function LaTeXDrawer() {
this._points = [];
this._texData = '';
this._scale = 0.1; // Ensure that the TikZ picture isn't too big
// Returns a string containing the LaTeX code that can easily be copied into a .tex file
this.toLaTeXCode = function()
{
return '\\begin{center}\n'
+ '\\begin{tikzpicture}[scale=0.2]\n'
+ '\\tikzstyle{every node}+=[inner sep=0pt]\n'
+ this._texData
+ '\\end{tikzpicture}\n'
+ '\\end{center}\n';
};
// Initialize drawing a line
this.beginPath = function()
{
this._points = [];
};
// Draw an arc
this.arc = function(x, y, radius, startAngle, endAngle, isReversed)
{
x *= this._scale;
y *= this._scale;
radius *= this._scale;
if (endAngle - startAngle == Math.PI * 2)
{
this._texData += '\\draw [' + this.strokeStyle + '] (' + fixed(x, 3) + ',' + fixed(-y, 3) + ') circle (' + fixed(radius, 3) + ');\n';
}
else
{
if (isReversed)
{
var temp = startAngle;
startAngle = endAngle;
endAngle = temp;
}
if (endAngle < startAngle)
{
endAngle += Math.PI * 2;
}
// TikZ should have angles between -2PI and 2PI
if (Math.min(startAngle, endAngle) < -2*Math.PI) {
startAngle += 2*Math.PI;
endAngle += 2*Math.PI;
}
else if (Math.max(startAngle, endAngle) > 2*Math.PI)
{
startAngle -= 2*Math.PI;
endAngle -= 2*Math.PI;
}
startAngle = -startAngle;
endAngle = -endAngle;
this._texData += '\\draw [' + this.strokeStyle + '] (' + fixed(x + radius * Math.cos(startAngle), 3)
+ ',' + fixed(-y + radius * Math.sin(startAngle), 3) + ') arc ('
+ fixed(startAngle * 180 / Math.PI, 5) + ':' + fixed(endAngle * 180 / Math.PI, 5) + ':'
+ fixed(radius, 3) + ');\n';
}
};
// Draw a line i.e. push a start point or end point
this.moveTo = this.lineTo = function(x, y)
{
x *= this._scale;
y *= this._scale;
this._points.push({ 'x': x, 'y': y });
};
// For each point, output its LaTeX code
this.stroke = function()
{
var length = this._points.length;
if (length == 0)
{
return;
}
this._texData += '\\draw [' + this.strokeStyle + ']';
for (var i = 0; i < length; i++)
{
var p = this._points[i];
this._texData += (i > 0 ? ' --' : '') + ' (' + fixed(p.x, 2) + ',' + fixed(-p.y, 2) + ')';
}
this._texData += ';\n';
};
this.fill = function()
{
if (this._points.length == 0)
{
return;
}
this._texData += '\\fill [' + this.strokeStyle + ']';
for (var i = 0, n = this._points.length; i < n; i++)
{
var p = this._points[i];
this._texData += (i > 0 ? ' --' : '') + ' (' + fixed(p.x, 2) + ',' + fixed(-p.y, 2) + ')';
}
this._texData += ';\n';
};
// Return the width of the text
this.measureText = function(text)
{
var c = canvas.getContext('2d');
c.font = FONT_SIZE + 'px ' + FONT + ', serif';
return c.measureText(text);
};
// Draw text smartly, using an x, y offset
this.advancedFillText = function(text, originalText, x, y, angle)
{
if (text.replace(' ', '').length > 0)
{
var nodeParams = '';
if (angle != null)
{
var width = this.measureText(text).width;
var dx = Math.cos(angleOrNull);
var dy = Math.sin(angleOrNull);
if (Math.abs(dx) > Math.abs(dy))
{
if (dx > 0)
{
nodeParams = '[right] '; x -= width / 2;
}
else
{
nodeParams = '[left] '; x += width / 2;
}
}
else
{
if (dy > 0)
{
nodeParams = '[below] '; y -= 10;
}
else
{
nodeParams = '[above] '; y += 10;
}
}
}
x *= this._scale;
y *= this._scale;
var subscriptedText = this.makeLaTeXSubscripts(originalText);
this._texData += '\\draw (' + fixed(x, 2) + ',' + fixed(-y, 2) + ') node '
+ nodeParams + '{$' + subscriptedText.replace(/ /g, '\\mbox{ }') + '$};\n';
}
};
// Make LaTeX subscripts using regular expressions
// Converts any numbers between _ and _ to the proper braces _{} LaTeX uses
this.makeLaTeXSubscripts = function(text)
{
var subscripts = text.match(new RegExp('_[0-9]+_', 'g'));
if (subscripts != null)
{
var length = subscripts.length;
var replace = new Array(length);
for (var i = 0; i < length; i++)
{
replace[i] = '_{';
replace[i] += subscripts[i].replace(new RegExp('_', 'g'), '');
replace[i] += '}';
text = text.replace(new RegExp(subscripts[i], 'g'), replace[i]);
}
}
return text;
};
this.translate = this.save = this.restore = this.clearRect = function(){};
}
// Export as PNG file
function saveAsPNG()
{
var old = selectedObject;
selectedObject = null;
drawWith(canvas.getContext('2d'));
selectedObject = old;
var png = canvas.toDataURL('image/png');
document.location.href = png;;
}
// Export as LaTeX code
function saveAsLaTeX()
{
var latex = new LaTeXDrawer();
var old = selectedObject;
selectedObject = null;
drawWith(latex);
selectedObject = old;
var texCode = latex.toLaTeXCode();
output(texCode);
}
// To convert a number to a string with two decimals, needed to LaTeX code
function fixed(number, digits)
{
return number.toFixed(digits).replace(/0+$/, '').replace(/\.$/, '');
}
// Output to a textbox (named output in our html file)
function output(text)
{
var element = document.getElementById('output');
element.style.display = 'block';
element.value = text;
}
// Make subscripts for displaying in our canvas
// Any numbers in between two underscores are subscripts
// Example: _3_ or _123_
function makeSubscripts(text)
{
var subscripts = text.match(new RegExp('_[0-9]+_', 'g'));
if (subscripts != null)
{
var length = subscripts.length;
var replace = new Array(length);
for (var i = 0; i < length; i++)
{
replace[i] = subscripts[i].replace(new RegExp('_|_', 'g'), '');
for (var j = 0; j < 10; j++)
{
replace[i] = replace[i].replace(new RegExp(j, 'g'), String.fromCharCode(8320 + j));
}
text = text.replace(new RegExp(String(subscripts[i]), 'g'), replace[i]);
}
}
return text;
}
// Undirected edge between two vertices v1 and v2
function Edge(v1, v2)
{
this.v1 = v1;
this.v2 = v2;
this.text = '';
}
// Draw the edge: only a line since it's undirected
Edge.prototype.draw = function(c)
{
// Nearest points on v1, v2 circles
var point1 = this.v1.nearestCirclePoint(this.v2.x, this.v2.y);
var point2 = this.v2.nearestCirclePoint(this.v1.x, this.v1.y);
c.beginPath();
c.moveTo(point1.x, point1.y);
c.lineTo(point2.x, point2.y);
c.stroke();
var midX = (point2.x + point1.x) / 2;
var midY = (point2.y + point1.y) / 2;
var angle = Math.atan2(point2.x - point1.x, point2.y - point1.y);
// Draw text
drawText(c, this.text, midX, midY, angle, false);
};
// Check if edge contains a point (x, y)
Edge.prototype.contains = function(x, y)
{
var dx = this.v2.x - this.v1.x;
var dy = this.v2.y - this.v1.y;
var length = Math.sqrt(dx * dx + dy * dy);
var percent = (dx * (x - this.v1.x) + dy * (y - this.v1.y)) / (length * length);
var dist = (dx * (y - this.v1.y) - dy * (x - this.v1.x)) / length;
return (percent > 0 && percent < 1 && Math.abs(dist) < EDGE_MARGIN);
};
// Temporary edge from a source vertex to a point
function TempEdge(vertex, dest)
{
this.vertex = vertex;
this.dest = dest;
}
// Drawing function for the edge
TempEdge.prototype.draw = function(c)
{
var point = this.vertex.nearestCirclePoint(this.dest.x, this.dest.y);
c.beginPath();
c.moveTo(point.x, point.y);
c.lineTo(this.dest.x, this.dest.y);
c.stroke();
}
// Directed edge
function DirEdge(v1, v2)
{
this.v1 = v1;
this.v2 = v2;
this.text = '';
}
// Draw a directed edge, with an arrow
DirEdge.prototype.draw = function(c)
{
c.beginPath();
// Nearest points on vertex circles
var point1 = this.v1.nearestCirclePoint(this.v2.x, this.v2.y);
var point2 = this.v2.nearestCirclePoint(this.v1.x, this.v1.y);
c.moveTo(point1.x, point1.y);
c.lineTo(point2.x, point2.y);
c.stroke();
// Draw the arrow
drawArrow(c, point2.x, point2.y, Math.atan2(point2.y - point1.y, point2.x - point1.x));
var midX = (point2.x + point1.x) / 2;
var midY = (point2.y + point1.y) / 2;
var angle = Math.atan2(point2.x - point1.x, point2.y - point1.y);
// Draw text
drawText(c, this.text, midX, midY, angle, false);
};
// Check whether the edge contains a point (x, y) (for selecting the edge)
DirEdge.prototype.contains = function(x, y)
{
var dx = this.v2.x - this.v1.x;
var dy = this.v2.y - this.v1.y;
var length = Math.sqrt(dx * dx + dy * dy);
var percent = (dx * (x - this.v1.x) + dy * (y - this.v1.y)) / (length * length);
var dist = (dx * (y - this.v1.y) - dy * (x - this.v1.x)) / length;
return (percent > 0 && percent < 1 && Math.abs(dist) < EDGE_MARGIN);
};
// Temporary directed edge from a source vertex to a point
function TempDirEdge(vertex, dest)
{
this.vertex = vertex;
this.dest = dest;
}
// Drawing function
TempDirEdge.prototype.draw = function(c)
{
var point = this.vertex.nearestCirclePoint(this.dest.x, this.dest.y);
c.beginPath();
c.moveTo(point.x, point.y);
c.lineTo(this.dest.x, this.dest.y);
c.stroke();
drawArrow(c, this.dest.x, this.dest.y, Math.atan2(this.dest.y - point.y, this.dest.x - point.x));
}
function Vertex(x, y)
{
this.x = x;
this.y = y;
this.radius = VERTEX_RADIUS;
this.mouseOffsetX = 0;
this.mouseOffsetY = 0;
this.text = '';
}
Vertex.prototype.draw = function(c)
{
// Change vertex radius if text width is too large or small
var textWithoutSubscripts = makeSubscripts(this.text);
var width = c.measureText(textWithoutSubscripts).width;
if (width < 2 * VERTEX_RADIUS - VERTEX_RADIUS / 3)
{
this.radius = VERTEX_RADIUS;
}
else
{
this.radius = width / 2 + VERTEX_PADDING;
}
// Draw the vertex circle
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
c.stroke();
// Draw the text
drawText(c, this.text, this.x, this.y, null, selectedObject == this);
};
// Check if a point is inside the vertex
Vertex.prototype.contains = function(x, y)
{
var dx = x - this.x;
var dy = y - this.y;
return dx * dx + dy * dy <= this.radius * this.radius;
};
// Find the nearest point on the edge of the circle to the given coordinates
Vertex.prototype.nearestCirclePoint = function(x, y)
{
var dx = x - this.x;
var dy = y - this.y;
var dist = Math.sqrt(dx * dx + dy * dy);
return {
'x': this.x + this.radius * dx / dist,
'y': this.y + this.radius * dy / dist
};
};
// Keep track of start point (for moving vertices), so that later, we can move vertex without having to center it on the mouse
Vertex.prototype.setStartPoint = function(x, y)
{
this.mouseOffsetX = this.x - x;
this.mouseOffsetY = this.y - y;
};
// Set the position of the vertex, using the offset point set earlier
Vertex.prototype.setAnchorPoint = function(x, y)
{
this.x = x + this.mouseOffsetX;
this.y = y + this.mouseOffsetY;
};