d3力导向图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script type="text/javascript" src="../d3.js"></script>-->
<script src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<style>
svg{
background-color: #ccc;
}
</style>
<script>
let dataset={
nodes: [
{ name: "Adam" },
{ name: "Bob" },
{ name: "Carrie" },
{ name: "Donovan" },
{ name: "Edward" },
{ name: "Felicity" },
{ name: "George" },
{ name: "Hannah" },
{ name: "Iris" },
{ name: "Jerry" }
],
edges: [
{ source: 0, target: 1 },
{ source: 0, target: 2 },
{ source: 0, target: 3 },
{ source: 0, target: 4 },
{ source: 1, target: 5 },
{ source: 2, target: 5 },
{ source: 2, target: 5 },
{ source: 3, target: 4 },
{ source: 5, target: 8 },
{ source: 5, target: 9 },
{ source: 6, target: 7 },
{ source: 7, target: 8 },
{ source: 8, target: 9 }
]
}
let width=800
let height=500
let svg=d3.select('body').append('svg').attr('width',width).attr('height',height)
let force=d3.forceSimulation(dataset.nodes)
.force('charge',d3.forceManyBody())
.force('link',d3.forceLink(dataset.edges))
.force('center',d3.forceCenter().x(width/2).y(height/2))
let color=d3.scaleOrdinal(d3.schemeCategory10)
let edges=svg.selectAll('line')
.data(dataset.edges)
.enter()
.append('line')
.style('stroke','red')
.style('stroke-width',1)
let nodes=svg.selectAll('.node')
.data(dataset.nodes)
.enter()
.append('g')
.call(d3.drag()
.on('start',dragStarted)
.on('drag',dragging)
.on('end',dragEnded)
)
nodes.append('circle')
.attr('r',15)
.style('fill',function (d,i){
return color(i)
})
nodes.append("text")
// 文字内容
.text(function (d) {
return d.name;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "red");
force.on('tick',function (){
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})
// nodes.attr('cx',function (d){return d.x})
// .attr('cy',function (d){return d.y})
d3.selectAll("circle")
.attr("cx", function (d) {
return d.x;
})
.attr("cy", function (d) {
return d.y;
});
d3.selectAll("text")
.attr("x", function (d) {
return d.x;
})
.attr("y", function (d) {
return d.y;
});
})
function dragStarted(d){
if(!d3.event.active) force.alphaTarget(0.3).restart()
d.fx=d.x
d.fy=d.y
}
function dragging(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragEnded(d) {
if (!d3.event.active) force.alphaTarget(0);
d.fx = null;
d.fy = null;
}
</script>
</body>
</html>