我正在制作d3力图,我想在每个节点上发布一些文字。我在互联网上搜索,我只找到了SVG解决方案,但在我的代码中,我没有使用SVG,但我发现你可以使用像鼠标一样的d3事件,我不明白如何把它放在我的代码中。< / p>
有了这个代码结构,任何人都可以帮我解决我的问题吗?
<body>
<h1>Graph</h1>
<canvas id="network" width="1000" height="1000"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
/* global d3 */
var canvas = d3.select("#network"),
width = canvas.attr("width"),
height = canvas.attr("height"),
ctx = canvas.node().getContext("2d"),
r = 10,
x = d3.scaleOrdinal().range([20,width -20]),
color = d3.scaleOrdinal(d3.schemeCategory20),
simulation = d3.forceSimulation()
.force("x", d3.forceX(width/2))
.force("y", d3.forceY(height/2))
.force("collide", d3.forceCollide(r+1))
.force("charge", d3.forceManyBody()
.strength(-200))
.force("link", d3.forceLink()
.id(function (d) { return d.champion; }));
d3.json("docs/Champions.json", function (err, graph) {
if (err) throw err;
simulation.nodes(graph.nodes);
simulation.force("link")
.links(graph.links);
simulation.on("tick", update);
canvas
.call(d3.drag()
.container(canvas.node())
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
function update() {
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.globalAlpha = 0.5;
ctx.strokeStyle = "#808080";
graph.links.forEach(drawLink);
ctx.stroke();
ctx.globalAlpha = 1.0;
graph.nodes.forEach(drawNode);
}
function dragsubject() {
return simulation.find(d3.event.x, d3.event.y);
}
});
function dragstarted() {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
console.log(d3.event.subject.champion);
}
function dragged() {
d3.event.subject.fx = d3.event.x;
d3.event.subject.fy = d3.event.y;
}
function dragended() {
if (!d3.event.active) simulation.alphaTarget(0);
d3.event.subject.fx = null;
d3.event.subject.fy = null;
}
function drawNode(d) {
ctx.beginPath();
ctx.fillStyle = color(d.region);
ctx.moveTo(d.x, d.y);
ctx.arc(d.x, d.y, r, 0, Math.PI*2);
ctx.fill();
}
function drawLink(l) {
ctx.moveTo(l.source.x, l.source.y);
ctx.lineTo(l.target.x, l.target.y);
}
</script>
</body>
</html>
我使用的JSON文件就像
{ "nodes": [
{"champion":"name",
"region":"place"},
{...}
],
"links": [
{"source": "...",
"target":"..."},
{...}
]}
答案 0 :(得分:0)
这已经有一段时间了,但是因为我也想知道如何实现原问题中的问题,这里是记录的解决方案:
为了添加来自例如在JSON文件的“冠军”字段中,添加以下行:
ctx.fillText(d.champion, d.x, d.y);
到函数:
function drawNode(d)
e.g:
function drawNode(d) {
ctx.beginPath();
ctx.fillStyle = color(d.region);
ctx.moveTo(d.x, d.y);
ctx.arc(d.x, d.y, r, 0, Math.PI*2);
ctx.fill();
ctx.fillText(d.champion, d.x, d.y);
}