如何设置箭头的方向? [英] How to set the direction of the arrowhead?
问题描述
这是我以前的问题:我需要根据一列flag
(右侧为R
,左侧为L
)在一侧添加一个箭头:
I need to add an arrow head at one side, based on one column flag
(R
for right, L
for left):
x1,y1,x2,y2,Flag
1,2,3,2,L
3,3,5,3,R
5,3,6,3,L
7,5,7,5,R
8,6,8,6,L
9,7,2,7,L
怎么可能?
推荐答案
此处最明显的解决方案是根据flag
属性的值将标记设置为marker-end
或marker-start
.
The most obvious solution here would be setting the marker as marker-end
or marker-start
according to the value of the flag
property.
但是,再三考虑一下,我们可以在此处做一些更有趣的事情:我们可以将所有标记设置为marker-end
,然后根据flag
,我们交换 x1
和x2
属性,使得:
However, on a second thought, we can do something more interesting here: we can set all markers as marker-end
and, according to the flag
, we swap the x1
and x2
properties, making:
-
如果标志为
-
x1
小于x2
;
如果标志为 -
x1
大于x2
;
R
,则L
,则x1
smaller thanx2
if flag isR
;x1
bigger thanx2
if flag isL
;
可以通过以下方式完成:
It can be done with:
data.forEach(function(d) {
if ((d.flag === "L" && d.x1 < d.x2) || (d.flag === "R" && d.x1 > d.x2)) {
d.x1 = d.x2 + (d.x2 = d.x1, 0);
}
});
这是演示:
const csv = `x1,y1,x2,y2,flag
1,2,3,2,L
3,3,5,4,R
5,3,6,3,L
7,5,8,5,R
8,6,9,6,L
9,7,2,8,L`;
const data = d3.csvParse(csv, function(d) {
d.x1 = +d.x1 * 20;
d.y1 = +d.y1 * 15;
d.x2 = +d.x2 * 20;
d.y2 = +d.y2 * 15;
return d;
});
data.forEach(function(d) {
if ((d.flag === "L" && d.x1 < d.x2) || (d.flag === "R" && d.x1 > d.x2)) d.x1 = d.x2 + (d.x2 = d.x1, 0);
});
const svg = d3.select("svg");
const marker = svg.append("defs")
.append("marker")
.attr("id", "marker")
.attr("viewBox", "0 0 10 10")
.attr("refX", "5")
.attr("refY", "5")
.attr("markerWidth", "6")
.attr("markerHeight", "6")
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 L 10 5 L 0 10 z");
const enterSelection = svg.selectAll(null)
.data(data)
.enter()
.append("line")
.attr("x1", d => d.x1)
.attr("y1", d => d.y1)
.attr("x2", d => d.x2)
.attr("y2", d => d.y2)
.attr("marker-end", "url(#marker)")
.style("stroke-width", "1px")
.style("stroke", "black");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>
由于您的值太小,因此我在此处将它们相乘,以便我们更好地看到线条.另外,因为您没有共享任何标记,所以我在
Since your values are too small I'm multiplying them here, so we can better see the lines. Also, because you didn't share any marker, I'm using the one at MDN.
这篇关于如何设置箭头的方向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!