在力导向图中将文本居中放置在曲线链接上
Center text over curved links in a force-directed graph
这是第二个问题,它基于我之前在这里提出的一个问题 - - 关于如何缩短 d3 力图的弯曲链接。
我最近的努力涉及将放置在链接顶部的文本居中,实际上是在链接上方。这是一个显示我的问题的可重现示例(对于长代码表示歉意。创建一个可重现示例需要很多,尽管我目前只处理其中的一小部分):
const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")
var graphs = {
"nodes": [{
"name": "Peter",
"label": "Person",
"id": 1
},
{
"name": "Michael",
"label": "Person",
"id": 2
},
{
"name": "Neo4j",
"label": "Database",
"id": 3
},
{
"name": "Graph Database",
"label": "Database",
"id": 4
}
],
"links": [{
"source": 1,
"target": 2,
"type": "KNOWS",
"since": 2010
},
{
"source": 1,
"target": 3,
"type": "FOUNDED"
},
{
"source": 2,
"target": 3,
"type": "WORKS_ON"
},
{
"source": 3,
"target": 4,
"type": "IS_A"
}
]
}
svg.append('defs').append('marker')
.attr('id', 'arrowhead')
.attr('viewBox', '-0 -5 10 10')
.attr('refX', 0)
.attr('refY', 0)
.attr('orient', 'auto')
.attr('markerWidth', 13)
.attr('markerHeight', 13)
.attr('xoverflow', 'visible')
.append('svg:path')
.attr('d', 'M 0,-5 L 10 ,0 L 0,5')
.attr('fill', '#999')
.style('stroke', 'none');
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(100, 100));
let linksData = graphs.links.map(link => {
var obj = link;
obj.source = link.source;
obj.target = link.target;
return obj;
})
const links = linksG
.selectAll("g")
.data(graphs.links)
.enter().append("g")
.attr("cursor", "pointer")
const linkLines = links
.append("path")
.attr('stroke', '#000000')
.attr('opacity', 0.75)
.attr("stroke-width", 1)
.attr("fill", "transparent")
.attr('marker-end', 'url(#arrowhead)');
const linkText = links
.append("text")
.attr("x", d => (d.source.x + (d.target.x - d.source.x) * 0.5))
.attr("y", d => (d.source.y + (d.target.y - d.source.y) * 0.5))
.attr('stroke', '#000000')
.attr("text-anchor", "middle")
.attr('opacity', 1)
.text((d,i) => `${i}`);
const nodes = nodesG
.selectAll("g")
.data(graphs.nodes)
.enter().append("g")
.attr("cursor", "pointer")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
const circles = nodes.append("circle")
.attr("r", 12)
.attr("fill", "000000")
nodes.append("title")
.text(function(d) {
return d.id;
});
simulation
.nodes(graphs.nodes)
.on("tick", ticked);
simulation.force("link", d3.forceLink().links(linksData)
.id((d, i) => d.id)
.distance(150));
function ticked() {
linkLines.attr("d", function(d) {
var dx = (d.target.x - d.source.x),
dy = (d.target.y - d.source.y),
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
// recalculate and back off the distance
linkLines.attr("d", function(d) {
// length of current path
var pl = this.getTotalLength(),
// radius of circle plus backoff
r = (12) + 30,
// position close to where path intercepts circle
m = this.getPointAtLength(pl - r);
var dx = m.x - d.source.x,
dy = m.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
});
linkText
.attr("x", function(d) { return (d.source.x + (d.target.x - d.source.x) * 0.5); })
.attr("y", function(d) { return (d.source.y + (d.target.y - d.source.y) * 0.5); })
nodes
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>
</head>
<body>
<svg id="mySVG" width="500" height="500">
<g class="links" />
<g class="nodes" />
</svg>
我知道我的代码的问题在于此处 linkText 的 x 和 y 值设置:
linkText
.attr("x", function(d) { return (d.source.x + (d.target.x - d.source.x) * 0.5); })
.attr("y", function(d) { return (d.source.y + (d.target.y - d.source.y) * 0.5); })
...以及在我的代码的前面。我不确定如何更新这些函数以说明链接是曲线(不是从节点到节点的直线)这一事实。
我的项目的较大的力图有更多的链接和节点,最好将文本定位在弯曲的链接线的中心。
如有任何帮助,我们将不胜感激!
有几种不同的方法可以解决这个问题。最明显的两个是:
- 使用
getPointAtLength()
获取 <path>
的中间,并将文本定位在那里;
- 使用
<textPath>
元素。
在我的解决方案中,我会选择#2,主要是因为,使用文本路径,数字可以根据路径的方向翻转,其中一些最终颠倒(我假设这就是你想要的).
所以,我们附加 textPath
s...
const linkText = links
.append("text")
.attr("dy", -4)
.append("textPath")
.attr("xlink:href", function(_, i) {
return "#path" + i
})
.attr("startOffset", "50%")
.text((d, i) => `${i}`);
...已为路径提供唯一 ID:
.attr("id", function(_, i) {
return "path" + i
})
这是修改后的代码:
const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")
var graphs = {
"nodes": [{
"name": "Peter",
"label": "Person",
"id": 1
},
{
"name": "Michael",
"label": "Person",
"id": 2
},
{
"name": "Neo4j",
"label": "Database",
"id": 3
},
{
"name": "Graph Database",
"label": "Database",
"id": 4
}
],
"links": [{
"source": 1,
"target": 2,
"type": "KNOWS",
"since": 2010
},
{
"source": 1,
"target": 3,
"type": "FOUNDED"
},
{
"source": 2,
"target": 3,
"type": "WORKS_ON"
},
{
"source": 3,
"target": 4,
"type": "IS_A"
}
]
}
svg.append('defs').append('marker')
.attr('id', 'arrowhead')
.attr('viewBox', '-0 -5 10 10')
.attr('refX', 0)
.attr('refY', 0)
.attr('orient', 'auto')
.attr('markerWidth', 13)
.attr('markerHeight', 13)
.attr('xoverflow', 'visible')
.append('svg:path')
.attr('d', 'M 0,-5 L 10 ,0 L 0,5')
.attr('fill', '#999')
.style('stroke', 'none');
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(100, 100));
let linksData = graphs.links.map(link => {
var obj = link;
obj.source = link.source;
obj.target = link.target;
return obj;
})
const links = linksG
.selectAll("g")
.data(graphs.links)
.enter().append("g")
.attr("cursor", "pointer")
const linkLines = links
.append("path")
.attr("id", function(_, i) {
return "path" + i
})
.attr('stroke', '#000000')
.attr('opacity', 0.75)
.attr("stroke-width", 1)
.attr("fill", "transparent")
.attr('marker-end', 'url(#arrowhead)');
const linkText = links
.append("text")
.attr("dy", -4)
.append("textPath")
.attr("xlink:href", function(_, i) {
return "#path" + i
})
.attr("startOffset", "50%")
.attr('stroke', '#000000')
.attr('opacity', 1)
.text((d, i) => `${i}`);
const nodes = nodesG
.selectAll("g")
.data(graphs.nodes)
.enter().append("g")
.attr("cursor", "pointer")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
const circles = nodes.append("circle")
.attr("r", 12)
.attr("fill", "000000")
nodes.append("title")
.text(function(d) {
return d.id;
});
simulation
.nodes(graphs.nodes)
.on("tick", ticked);
simulation.force("link", d3.forceLink().links(linksData)
.id((d, i) => d.id)
.distance(150));
function ticked() {
linkLines.attr("d", function(d) {
var dx = (d.target.x - d.source.x),
dy = (d.target.y - d.source.y),
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
// recalculate and back off the distance
linkLines.attr("d", function(d) {
// length of current path
var pl = this.getTotalLength(),
// radius of circle plus backoff
r = (12) + 30,
// position close to where path intercepts circle
m = this.getPointAtLength(pl - r);
var dx = m.x - d.source.x,
dy = m.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
});
linkText
.attr("x", function(d) {
return (d.source.x + (d.target.x - d.source.x) * 0.5);
})
.attr("y", function(d) {
return (d.source.y + (d.target.y - d.source.y) * 0.5);
})
nodes
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>
</head>
<body>
<svg id="mySVG" width="500" height="500">
<g class="links" />
<g class="nodes" />
</svg>
另一方面,如果你不希望某些文字倒置,使用getPointAtLength()
获取路径的中间,即方法#1:
.attr("x", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length/2).x
})
.attr("y", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length/2).y
})
这是演示:
const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")
var graphs = {
"nodes": [{
"name": "Peter",
"label": "Person",
"id": 1
},
{
"name": "Michael",
"label": "Person",
"id": 2
},
{
"name": "Neo4j",
"label": "Database",
"id": 3
},
{
"name": "Graph Database",
"label": "Database",
"id": 4
}
],
"links": [{
"source": 1,
"target": 2,
"type": "KNOWS",
"since": 2010
},
{
"source": 1,
"target": 3,
"type": "FOUNDED"
},
{
"source": 2,
"target": 3,
"type": "WORKS_ON"
},
{
"source": 3,
"target": 4,
"type": "IS_A"
}
]
}
svg.append('defs').append('marker')
.attr('id', 'arrowhead')
.attr('viewBox', '-0 -5 10 10')
.attr('refX', 0)
.attr('refY', 0)
.attr('orient', 'auto')
.attr('markerWidth', 13)
.attr('markerHeight', 13)
.attr('xoverflow', 'visible')
.append('svg:path')
.attr('d', 'M 0,-5 L 10 ,0 L 0,5')
.attr('fill', '#999')
.style('stroke', 'none');
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(100, 100));
let linksData = graphs.links.map(link => {
var obj = link;
obj.source = link.source;
obj.target = link.target;
return obj;
})
const links = linksG
.selectAll("g")
.data(graphs.links)
.enter().append("g")
.attr("cursor", "pointer")
const linkLines = links
.append("path")
.attr('stroke', '#000000')
.attr('opacity', 0.75)
.attr("stroke-width", 1)
.attr("fill", "transparent")
.attr('marker-end', 'url(#arrowhead)');
const linkText = links
.append("text")
.attr("x", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length / 2).x
})
.attr("y", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length / 2).y
})
.attr('stroke', '#000000')
.attr("text-anchor", "middle")
.attr("dominant-baseline", "central")
.attr('opacity', 1)
.text((d, i) => `${i}`);
const nodes = nodesG
.selectAll("g")
.data(graphs.nodes)
.enter().append("g")
.attr("cursor", "pointer")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
const circles = nodes.append("circle")
.attr("r", 12)
.attr("fill", "000000")
nodes.append("title")
.text(function(d) {
return d.id;
});
simulation
.nodes(graphs.nodes)
.on("tick", ticked);
simulation.force("link", d3.forceLink().links(linksData)
.id((d, i) => d.id)
.distance(150));
function ticked() {
linkLines.attr("d", function(d) {
var dx = (d.target.x - d.source.x),
dy = (d.target.y - d.source.y),
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
// recalculate and back off the distance
linkLines.attr("d", function(d) {
// length of current path
var pl = this.getTotalLength(),
// radius of circle plus backoff
r = (12) + 30,
// position close to where path intercepts circle
m = this.getPointAtLength(pl - r);
var dx = m.x - d.source.x,
dy = m.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
});
linkText
.attr("x", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length / 2).x
})
.attr("y", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length / 2).y
})
nodes
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>
</head>
<body>
<svg id="mySVG" width="500" height="500">
<g class="links" />
<g class="nodes" />
</svg>
这里我假设 <path>
是 <text>
的前一个兄弟。如果实际代码不是这种情况,请相应地更改它。
这是第二个问题,它基于我之前在这里提出的一个问题 -
我最近的努力涉及将放置在链接顶部的文本居中,实际上是在链接上方。这是一个显示我的问题的可重现示例(对于长代码表示歉意。创建一个可重现示例需要很多,尽管我目前只处理其中的一小部分):
const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")
var graphs = {
"nodes": [{
"name": "Peter",
"label": "Person",
"id": 1
},
{
"name": "Michael",
"label": "Person",
"id": 2
},
{
"name": "Neo4j",
"label": "Database",
"id": 3
},
{
"name": "Graph Database",
"label": "Database",
"id": 4
}
],
"links": [{
"source": 1,
"target": 2,
"type": "KNOWS",
"since": 2010
},
{
"source": 1,
"target": 3,
"type": "FOUNDED"
},
{
"source": 2,
"target": 3,
"type": "WORKS_ON"
},
{
"source": 3,
"target": 4,
"type": "IS_A"
}
]
}
svg.append('defs').append('marker')
.attr('id', 'arrowhead')
.attr('viewBox', '-0 -5 10 10')
.attr('refX', 0)
.attr('refY', 0)
.attr('orient', 'auto')
.attr('markerWidth', 13)
.attr('markerHeight', 13)
.attr('xoverflow', 'visible')
.append('svg:path')
.attr('d', 'M 0,-5 L 10 ,0 L 0,5')
.attr('fill', '#999')
.style('stroke', 'none');
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(100, 100));
let linksData = graphs.links.map(link => {
var obj = link;
obj.source = link.source;
obj.target = link.target;
return obj;
})
const links = linksG
.selectAll("g")
.data(graphs.links)
.enter().append("g")
.attr("cursor", "pointer")
const linkLines = links
.append("path")
.attr('stroke', '#000000')
.attr('opacity', 0.75)
.attr("stroke-width", 1)
.attr("fill", "transparent")
.attr('marker-end', 'url(#arrowhead)');
const linkText = links
.append("text")
.attr("x", d => (d.source.x + (d.target.x - d.source.x) * 0.5))
.attr("y", d => (d.source.y + (d.target.y - d.source.y) * 0.5))
.attr('stroke', '#000000')
.attr("text-anchor", "middle")
.attr('opacity', 1)
.text((d,i) => `${i}`);
const nodes = nodesG
.selectAll("g")
.data(graphs.nodes)
.enter().append("g")
.attr("cursor", "pointer")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
const circles = nodes.append("circle")
.attr("r", 12)
.attr("fill", "000000")
nodes.append("title")
.text(function(d) {
return d.id;
});
simulation
.nodes(graphs.nodes)
.on("tick", ticked);
simulation.force("link", d3.forceLink().links(linksData)
.id((d, i) => d.id)
.distance(150));
function ticked() {
linkLines.attr("d", function(d) {
var dx = (d.target.x - d.source.x),
dy = (d.target.y - d.source.y),
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
// recalculate and back off the distance
linkLines.attr("d", function(d) {
// length of current path
var pl = this.getTotalLength(),
// radius of circle plus backoff
r = (12) + 30,
// position close to where path intercepts circle
m = this.getPointAtLength(pl - r);
var dx = m.x - d.source.x,
dy = m.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
});
linkText
.attr("x", function(d) { return (d.source.x + (d.target.x - d.source.x) * 0.5); })
.attr("y", function(d) { return (d.source.y + (d.target.y - d.source.y) * 0.5); })
nodes
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>
</head>
<body>
<svg id="mySVG" width="500" height="500">
<g class="links" />
<g class="nodes" />
</svg>
我知道我的代码的问题在于此处 linkText 的 x 和 y 值设置:
linkText
.attr("x", function(d) { return (d.source.x + (d.target.x - d.source.x) * 0.5); })
.attr("y", function(d) { return (d.source.y + (d.target.y - d.source.y) * 0.5); })
...以及在我的代码的前面。我不确定如何更新这些函数以说明链接是曲线(不是从节点到节点的直线)这一事实。
我的项目的较大的力图有更多的链接和节点,最好将文本定位在弯曲的链接线的中心。
如有任何帮助,我们将不胜感激!
有几种不同的方法可以解决这个问题。最明显的两个是:
- 使用
getPointAtLength()
获取<path>
的中间,并将文本定位在那里; - 使用
<textPath>
元素。
在我的解决方案中,我会选择#2,主要是因为,使用文本路径,数字可以根据路径的方向翻转,其中一些最终颠倒(我假设这就是你想要的).
所以,我们附加 textPath
s...
const linkText = links
.append("text")
.attr("dy", -4)
.append("textPath")
.attr("xlink:href", function(_, i) {
return "#path" + i
})
.attr("startOffset", "50%")
.text((d, i) => `${i}`);
...已为路径提供唯一 ID:
.attr("id", function(_, i) {
return "path" + i
})
这是修改后的代码:
const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")
var graphs = {
"nodes": [{
"name": "Peter",
"label": "Person",
"id": 1
},
{
"name": "Michael",
"label": "Person",
"id": 2
},
{
"name": "Neo4j",
"label": "Database",
"id": 3
},
{
"name": "Graph Database",
"label": "Database",
"id": 4
}
],
"links": [{
"source": 1,
"target": 2,
"type": "KNOWS",
"since": 2010
},
{
"source": 1,
"target": 3,
"type": "FOUNDED"
},
{
"source": 2,
"target": 3,
"type": "WORKS_ON"
},
{
"source": 3,
"target": 4,
"type": "IS_A"
}
]
}
svg.append('defs').append('marker')
.attr('id', 'arrowhead')
.attr('viewBox', '-0 -5 10 10')
.attr('refX', 0)
.attr('refY', 0)
.attr('orient', 'auto')
.attr('markerWidth', 13)
.attr('markerHeight', 13)
.attr('xoverflow', 'visible')
.append('svg:path')
.attr('d', 'M 0,-5 L 10 ,0 L 0,5')
.attr('fill', '#999')
.style('stroke', 'none');
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(100, 100));
let linksData = graphs.links.map(link => {
var obj = link;
obj.source = link.source;
obj.target = link.target;
return obj;
})
const links = linksG
.selectAll("g")
.data(graphs.links)
.enter().append("g")
.attr("cursor", "pointer")
const linkLines = links
.append("path")
.attr("id", function(_, i) {
return "path" + i
})
.attr('stroke', '#000000')
.attr('opacity', 0.75)
.attr("stroke-width", 1)
.attr("fill", "transparent")
.attr('marker-end', 'url(#arrowhead)');
const linkText = links
.append("text")
.attr("dy", -4)
.append("textPath")
.attr("xlink:href", function(_, i) {
return "#path" + i
})
.attr("startOffset", "50%")
.attr('stroke', '#000000')
.attr('opacity', 1)
.text((d, i) => `${i}`);
const nodes = nodesG
.selectAll("g")
.data(graphs.nodes)
.enter().append("g")
.attr("cursor", "pointer")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
const circles = nodes.append("circle")
.attr("r", 12)
.attr("fill", "000000")
nodes.append("title")
.text(function(d) {
return d.id;
});
simulation
.nodes(graphs.nodes)
.on("tick", ticked);
simulation.force("link", d3.forceLink().links(linksData)
.id((d, i) => d.id)
.distance(150));
function ticked() {
linkLines.attr("d", function(d) {
var dx = (d.target.x - d.source.x),
dy = (d.target.y - d.source.y),
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
// recalculate and back off the distance
linkLines.attr("d", function(d) {
// length of current path
var pl = this.getTotalLength(),
// radius of circle plus backoff
r = (12) + 30,
// position close to where path intercepts circle
m = this.getPointAtLength(pl - r);
var dx = m.x - d.source.x,
dy = m.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
});
linkText
.attr("x", function(d) {
return (d.source.x + (d.target.x - d.source.x) * 0.5);
})
.attr("y", function(d) {
return (d.source.y + (d.target.y - d.source.y) * 0.5);
})
nodes
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>
</head>
<body>
<svg id="mySVG" width="500" height="500">
<g class="links" />
<g class="nodes" />
</svg>
另一方面,如果你不希望某些文字倒置,使用getPointAtLength()
获取路径的中间,即方法#1:
.attr("x", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length/2).x
})
.attr("y", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length/2).y
})
这是演示:
const svg = d3.select('#mySVG')
const nodesG = svg.select("g.nodes")
const linksG = svg.select("g.links")
var graphs = {
"nodes": [{
"name": "Peter",
"label": "Person",
"id": 1
},
{
"name": "Michael",
"label": "Person",
"id": 2
},
{
"name": "Neo4j",
"label": "Database",
"id": 3
},
{
"name": "Graph Database",
"label": "Database",
"id": 4
}
],
"links": [{
"source": 1,
"target": 2,
"type": "KNOWS",
"since": 2010
},
{
"source": 1,
"target": 3,
"type": "FOUNDED"
},
{
"source": 2,
"target": 3,
"type": "WORKS_ON"
},
{
"source": 3,
"target": 4,
"type": "IS_A"
}
]
}
svg.append('defs').append('marker')
.attr('id', 'arrowhead')
.attr('viewBox', '-0 -5 10 10')
.attr('refX', 0)
.attr('refY', 0)
.attr('orient', 'auto')
.attr('markerWidth', 13)
.attr('markerHeight', 13)
.attr('xoverflow', 'visible')
.append('svg:path')
.attr('d', 'M 0,-5 L 10 ,0 L 0,5')
.attr('fill', '#999')
.style('stroke', 'none');
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(100, 100));
let linksData = graphs.links.map(link => {
var obj = link;
obj.source = link.source;
obj.target = link.target;
return obj;
})
const links = linksG
.selectAll("g")
.data(graphs.links)
.enter().append("g")
.attr("cursor", "pointer")
const linkLines = links
.append("path")
.attr('stroke', '#000000')
.attr('opacity', 0.75)
.attr("stroke-width", 1)
.attr("fill", "transparent")
.attr('marker-end', 'url(#arrowhead)');
const linkText = links
.append("text")
.attr("x", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length / 2).x
})
.attr("y", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length / 2).y
})
.attr('stroke', '#000000')
.attr("text-anchor", "middle")
.attr("dominant-baseline", "central")
.attr('opacity', 1)
.text((d, i) => `${i}`);
const nodes = nodesG
.selectAll("g")
.data(graphs.nodes)
.enter().append("g")
.attr("cursor", "pointer")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
const circles = nodes.append("circle")
.attr("r", 12)
.attr("fill", "000000")
nodes.append("title")
.text(function(d) {
return d.id;
});
simulation
.nodes(graphs.nodes)
.on("tick", ticked);
simulation.force("link", d3.forceLink().links(linksData)
.id((d, i) => d.id)
.distance(150));
function ticked() {
linkLines.attr("d", function(d) {
var dx = (d.target.x - d.source.x),
dy = (d.target.y - d.source.y),
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
// recalculate and back off the distance
linkLines.attr("d", function(d) {
// length of current path
var pl = this.getTotalLength(),
// radius of circle plus backoff
r = (12) + 30,
// position close to where path intercepts circle
m = this.getPointAtLength(pl - r);
var dx = m.x - d.source.x,
dy = m.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
});
linkText
.attr("x", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length / 2).x
})
.attr("y", function(d) {
const length = this.previousSibling.getTotalLength();
return this.previousSibling.getPointAtLength(length / 2).y
})
nodes
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>
</head>
<body>
<svg id="mySVG" width="500" height="500">
<g class="links" />
<g class="nodes" />
</svg>
这里我假设 <path>
是 <text>
的前一个兄弟。如果实际代码不是这种情况,请相应地更改它。