-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.js
113 lines (88 loc) · 2.64 KB
/
graph.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
var graph = function () {
//
// private
//
var _force = null;
var _links = null;
var _link = null;
var _nodes = null;
var _node = null;
var _svg = null;
var _fill = null;
var _tick = function(){
_link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
_node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
};
var _restart = function(){
_link = _link.data(_links);
_link.enter().insert("line", ".node")
.attr("class", "link");
_node = _node.data(_nodes);
_node.enter().insert("circle", ".cursor")
.attr("class", "node")
.attr("r", 5);
_force.start();
};
return {
//
//public
//
width: 0,
height: 0,
create: function (width, height) {
if(!width) width = 960;
if(!height) height = 500;
this.width = width; this.height = height;
_fill = d3.scale.category20();
_force = d3.layout.force()
.size([width, height])
.nodes([{}]) // initialize with a single node
.linkDistance(30)
.charge(-60)
.on("tick", _tick);
_svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("id", "graph");
_svg.append("rect")
.attr("width", width)
.attr("height", height);
_nodes = _force.nodes();
_links = _force.links();
_node = _svg.selectAll(".node");
_link = _svg.selectAll(".link");
_restart();
},
createGraphFromJson: function(json){
_force = null;
_force = d3.layout.force()
.size([this.width, this.height])
.nodes(json.nodes) // initialize with a single node
.links(json.links)
.linkDistance(30)
.charge(-60)
.on("tick", _tick);
_nodes = _force.nodes();
_links = _force.links();
_node = _svg.selectAll(".node");
_link = _svg.selectAll(".link");
_restart();
},
createNode: function(xPos, yPos) {
if(!xPos) xPos = this.height/2;
if(!yPos) yPos = this.height/2;
_nodes.push({x: xPos, y: yPos});
_restart();
},
createEdge: function(nodeSource, nodeTarget) {
if(!nodeSource || !nodeTarget) return;
_links.push({source: nodeSource, target: nodeTarget});
_restart();
}
};
}()
graph.create(400 ,600);