主要利用d3.layout.force()生成的力导向布局器
const nodes = [{name: 1}, {name: 2}, {name: 3}, {name: 4}, {name: 5}, {name: 1}, {name: 2}, {name: 3}, {name: 4}, {name: 5}, {name: 6}, {name: 7}];
const edges = [{source: 0, target: 1}, {source: 0, target: 2}
, {source: 0, target: 3}
, {source: 0, target: 4}
, {source: 4, target: 5}
, {source: 6, target: 2}
, {source: 6, target: 3}
, {source: 7, target: 4}
, {source: 8, target: 5}
, {source: 10, target: 5}
, {source: 11, target: 7}
, {source: 9, target: 6}];
const width = 700, height = 500, padding = {top: 60, left: 30};
const svg = d3.select("body").append("svg").attr("width", width + padding.left * 2).attr("height", height + padding.top * 2);
const force = d3.layout.force().nodes(nodes).links(edges).size([width, height]).linkDistance(120).charge(-610);
force.start();
const color = d3.scale.category10();
const linearColor = d3.scale.category20();
// 创建拖拽监听事件
const dragEventor= force.drag().on("dragstart",function (d) {
// 每个节点都有一个fixed节点 设为true即固定
// 此固定是指不会受力的影响弹回去 不是不能拖动了
d.fixed = true;
}).on("dragend",function (d,i) {
// 拖拽结束后变成原来的颜色
d3.select(this).transition().attr("fill",color(i));
}).on("drag",function (d,i) {
// 拖拽时变色
d3.select(this).transition().attr("fill",linearColor(i));
});
const lines = svg.selectAll(".force-line").data(edges).enter()
.append("line")
.attr("class", "force-line");
const circles = svg.selectAll(".force-circle").data(nodes).enter()
.append("circle")
.attr("class", "force-circle")
// 开启拖拽
.call(force.drag)
// 绑定拖拽事件
.call(dragEventor);
const texts = svg.selectAll(".force-text").data(nodes).enter()
.append("text")
.attr("dy", ".3em")
.attr("class", "force-text");
force.on("tick", function () {
lines.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
});
circles.attr("r", 20)
.attr("cx", function (d) {
return d.x
}).attr("fill", function (d, i) {
return color(i);
}).attr("cy", function (d) {
return d.y
});
texts.attr("x", function (d) {
return d.x
}).attr("y", function (d) {
return d.y
}).text(function (d) {
return d.name;
});
});
结果: