d3.drawForceGraph = function ()
{
var nodes = [{ name: "桂林" }, { name: "广州" },
{ name: "厦门" }, { name: "杭州" },
{ name: "上海" }, { name: "青岛" },
{ name: "天津" }];
var edges = [{ source: 0, target: 1 }, { source: 0, target: 2 },
{ source: 0, target: 3 }, { source: 1, target: 4 },
{ source: 1, target: 5 }, { source: 1, target: 6 }];
var width = 800;
var height = 400;
if (svg == undefined)
{
svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
}
//=================创建力导向图生成器========================
var force = d3.layout.force()
.nodes(nodes) //指定节点数组
.links(edges) //指定连线数组
.size([width, height]) //指定范围
.linkDistance(100) //指定连线长度
.charge(-800); //相互之间的作用力(表示了节点间的分散程度)
force.start(); //开始作用
console.log(nodes);
console.log(edges);
console.log(d3.version);
var edgeGroup = svg.append("g");
var svg_edges = edgeGroup.selectAll("#glines")
.data(edges)
.enter()
.append("line")
.style("stroke", "#ccc")
.style("stroke-width", 3)
.attr("id", function (d, i) {
return "glines" + parseInt(i);
});
edgeGroup.attr("transform", "translate(" + 500 + "," + "20" + ")");
//var edgeGroup
//.call(force.drag);
var color = d3.scale.category20();
//添加节点
var nodeGroup = svg.append("g");
var svg_nodes = nodeGroup.selectAll("#circles")
.data(nodes)
.enter()
.append("circle")
.attr("r", 12)
.style("fill", function (d, i) {
return color(i);
})
.attr("id", function (d, i) {
return "circles" + parseInt(i);
})
.call(force.drag); //使得节点能够拖动
nodeGroup.attr("transform", "translate(" + 500 + "," + "20" + ")");
//添加描述节点的文字
var textGroup = svg.append("g");
var svg_texts = textGroup.selectAll("#texts")
.data(nodes)
.enter()
.append("text")
.style("fill", "black")
.attr("dx", 20)
.attr("dy", 8)
.attr("id", function (d, i) {
return "texts" + parseInt(i);
})
.text(function (d) {
return d.name;
}).call(force.drag);
textGroup.attr("transform", "translate(" + 500 + "," + "20" + ")");
//=========================不实现该事件函数,所有的点、线将聚合成一团=========================
force.on("tick", function () { //对于每一个时间间隔
//更新连线坐标
svg_edges.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; });
//更新节点坐标
svg_nodes.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; });
//更新文字坐标
svg_texts.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; });
});
}