3.x : API 中文手册 · d3/d3 Wiki · GitHub
4.x : d3/API.md at main · d3/d3 · GitHub
现在已经到5.x了
学习资源:API--中文手册 · D3.js API 中文手册 · 看云
d3-path - D3.js 帮助文档 - 开发文档 - 文江博客
需求:画系统关系图,9个系统,系统用圆表示,圆上要显示系统名,再用线将圆连在一起。
思路:先有svg,再添加线,再添加容器,容器中放入圆和标签。
注:标签文字颜色,用fill来设置,
因为标签定位用x和y,不好居中,所以用tranform来移动父容器定位
防止随机圆的坐标重叠,用force("collide")
let nodes = [
{id:'id1',category:"fixed",x:0, y:0, color:'#999'},
{id:'id2',category:"unfixed",x:100, y:100, color:'#999'},
{id:'id3',category:"fixed",x:300, y:200, color:'#999'}
]
let links=[
{source:'id1',target:'id2',color:'#000'},
{source:'id2',target:'id3',color:'#000'},
]
let width = 500, height: 700
let force = d3.forceSimulation().force("change",d3.forceManyBody())
.force("center",d3.forceCenter(width / 2 , height / 2))
.force("collide",d3.forceCollide().radius(60).iterations(2))
.on("tick",tick)
//防止重绘,先清理画布
d3.select('#content').selectAll('*').remove()
//添加svg
let svg = d3.select('#content').append("svg").attr('width',width).attr('height',height)
//先画线
let link = svg.selectAll(".link")
link = link.data(links).enter().append("line")
.attr("class","link")
.style("stroke",function(d){return d.color})
//再画圆(这样圆和标签会在线上)(标签要画在圆上,不能在圆内,至少需要和圆同级,先画圆,再画标签)
let node = svg.selectAll(".node").data(nodes).enter().appeng("g")
node.append("circle").attr("class","node")
.attr("style",d=>{return "fill:"+d.color+";stroke:"+d.color+";"})
.attr("r",d=>d.r)
.call(d3.drag())
node.append("text").attr("fill","#999")
.style('text-anchor','middle').style("font-size","14px")
.text(d=>d.name)
function tick(){
node.attr("cx",function(d){
if(d.category=='fixed'){
d.fx = nodes.find(i=>i.id == d.id).x
}
return d.x;
})
.attr("cy",function(d){
if(d.category=='fixed'){
d.fy = nodes.find(i=>i.id == d.id).y
}
return d.y;
})
.attr('transform',function(d){
let cx = d.x, cy = d.y
return 'translate('+cx+','+cy+')'
})
link.attr("x1",d=>d.source.x)
.attr("y1",d=>d.source.y)
.attr("x2",d=>d.target.x)
.attr("y2",d=>d.target.y)
}
如果line不能满足需求,可以改用path连接
一些小技巧:
1.在<style></style>里写的属性会覆盖 .attr()设置的属性,导致attr里属性值变了,但页面样式没变。
2.鼠标浮动显示提示,如果遇到莫名的提示消失,或者不提示,是因为没有给一些元素加上
.style("pointer-events","none")。
不提示:可能是因为鼠标移出,提示tooltip消失的位置是在元素上,如果提示tooltip没加这个属性,鼠标移到元素上的提示上,就会导致提示不显示。
莫名消失:可能是因为鼠标移到了元素上的文本text上,给文本text加上这个属性,就不影响了。
3.画入画布的元素顺序很重要,先画的在下面,所以一定要注意。要显示在最上面的后画。