d3js箭头未显示 [英] d3js arrowheads not showing
问题描述
我有一个力向图的例子.而且我想显示箭头,但是无论我尝试了什么,我都看不到它们.
I have an example of force directed graph. And i want to show arrowheads, but no matter what i tried i can't see them.
这是我的JavaScript
Here is my javascript
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {
name: link.source
});
link.target = nodes[link.target] || (nodes[link.target] = {
name: link.target
});
});
var width = 960,
height = 500;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.linkDistance(100)
.charge(-300)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("svg:defs").selectAll("marker")
.data(["arrow"])
.enter().append("svg:marker")
.attr("id", "arrow")
.attr("viewBox","0 0 10 10")
.attr("refX","20")
.attr("refY","5")
.attr("markerUnits","strokeWidth")
.attr("markerWidth","9")
.attr("markerHeight","5")
.attr("orient","auto")
.append("svg:path")
.attr("d","M 0 0 L 10 5 L 0 10 z")
.attr("fill", "#f0f0f0");
var link = svg.append("svg:g").selectAll("line")
.data(force.links())
.enter().append("svg:line")
.attr("class", "link")
.attr("marker-mid", "url(#arrow)");
var node = svg.append("svg:g").selectAll(".node")
.data(force.nodes())
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", 8);
node.append("text")
.attr("x", -22)
.text(function(d) {
return d.name;
});
function tick() {
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;
});
link.attr("marker-mid", "url(#arrow)");
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
推荐答案
来自 marker-mid
上的MDN文档:
From the MDN docu on marker-mid
:
标记中间定义了箭头或多标记,应在给定元素或基本形状的除第一个和最后一个顶点以外的每个顶点上绘制.
The marker-mid defines the arrowhead or polymarker that shall be drawn at every vertex other than the first and last vertex of the given element or basic shape.
因此标记将插入到每个顶点,但要插入起点和终点.
So the marker will be inserted at every vertex, but the start and end.
但是,简单的线段没有其他顶点,只有起点和终点.因此,您的代码中没有显示标记.
A simple line segment, however, has no other vertices, but its start and end. Thus there are no markers shown in your code.
如果将marker-mid
更改为例如marker-end
,则会看到箭头(尽管现在它们还不那么漂亮):
If you change your marker-mid
to, e.g., marker-end
, you will see the arrow heads (although right now, they are not that pretty): fiddle.
另一种方法是将line
元素更改为path
元素,并在中间添加一个附加顶点.但是,这将需要一些足够的代码.
Another way, would be to change the line
-elements to path
elements and add a additional vertex in the mid. This, however, would require some more sufficient code.
这篇关于d3js箭头未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!