在这个小提琴中,我试图画一个箭头:
var svgContainer = d3.select("body").append("svg")
.attr("width", 1200)
.attr("height", 1200)
.attr("text-align" , "center");
var arrowStartPosition = 5
var arrowSpacing = 60
var verticalStrokeColor = "black"
var arrowYStartPosition = 5
var arrowYEndStartPosition = 150
var margin = 150;
var labelLine = svgContainer.append("line")
.attr("x1", arrowStartPosition + margin)
.attr("y1", arrowYStartPosition)
.attr("x2", arrowStartPosition + margin)
.attr("y2", arrowYEndStartPosition)
.attr("stroke-width", 2)
.attr("stroke", verticalStrokeColor);
var right = svgContainer.append("line")
.attr("x1", arrowStartPosition + margin)
.attr("y1", arrowYStartPosition)
.attr("x2", 20 + margin)
.attr("y2", 20)
.attr("stroke-width", 2)
.attr("stroke", "black");
var left = svgContainer.append("line")
.attr("x1", right.attr("x1")-15)
.attr("y1", right.attr("y1")+15)
.attr("x2", 5 + margin)
.attr("y2", 5)
.attr("stroke-width", 2)
.attr("stroke", "black");
为了尝试保持代码通用,我试图根据右边的位置继续绘制箭头的左侧部分:
.attr("y1", right.attr("y1")+15)
但是可以在小提琴中看到:
http://jsfiddle.net/Qh9X5/3447/
没有正确绘制箭头。
我认为这是因为right.attr("y1")
值在绘制时未初始化?
任何关于更优雅的方法的指针都能达到同样的效果。
答案 0 :(得分:1)
无需JavaScript!使用SVG <marker/>
:
<svg>
<defs>
<marker id="arrow-head" markerWidth="13" markerHeight="13" refx="5" refy="5" orient="auto">
<path d="M0,0 L0,10 L10,5 L0,0" style="fill: #000000;" />
</marker>
</defs>
<path d="M0,0 L10,20 L20,50 L30,30 L40,40 L50,50" style="stroke: #000000; stroke-width: 1px; fill: none; marker-end: url(#arrow-head);"/>
</svg>
答案 1 :(得分:0)
如果您要根据右侧的位置定义左侧位置,则唯一需要更改的值为x2
。
var left = svgContainer.append("line")
.attr("x1", right.attr("x1"))
.attr("y1", right.attr("y1"))
.attr("x2", right.attr("x2")-30)
.attr("y2", right.attr("y2"))
.attr("stroke-width", 2)
.attr("stroke", "black");