D3制作力导向图

复制代码
<script type="text/javascript">
const width = 1200, height = 1000;

const tooltip = d3.select('body')
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("color", '#5F9EA0')
.style('visibility', 'hidden')
.style('font-size', '12px')
.style('font-weight', 'bold')
.text('');

const force = d3.layout.force()
.charge(-1000).linkDistance(150).size([width, height]);

const svg = d3.select("#graph").append("svg")
.attr("width", width).attr("height", height)
.attr("pointer-events", "all");


d3.json("/graph", function(error, graph) {
if (error) return;

force.nodes(graph.nodes).links(graph.links).start();

const g = svg.append("g");

const link = svg.select("g").selectAll(".link")
.data(graph.links).enter()
.append("line").attr("class", "link");

const node = svg.select("g").selectAll(".node")
.data(graph.nodes).enter()
.append("circle")
.attr("class", function (d) { return "node "+d.label })
.attr("r", 20)
.on("mouseover", function(d,i){
//TOOLTIP
tooltip.style('visibility','visible').text(d.name)
})
.call(force.drag);

const nodeText = svg.select("g").selectAll("text")
.data(graph.nodes).enter()
.append("text")
.attr('dy', '.3em') //偏移量
.attr('text-anchor', 'middle') //text放在节点中心
.style('fill', 'black')
.style('pointer-events', 'none')
.text(function(d){return d.name;})




// force feed algo ticks
force.on("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; });

nodeText.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; });

});


});
</script>
复制代码

 

posted @   徐钏  阅读(236)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示