如何设置箭头的方向?

时间:2019-03-20 01:51:40

标签: javascript d3.js svg

这是我以前的问题:How to draw line automatically by reading coordinates from file?

我需要根据--profile-directory="My Name As Profile"的一列在箭头的一侧添加一个箭头(右侧为<?xml version="1.0" encoding="utf-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <?define ComponentRules="OneToOne"?> <!-- SourceDir instructs IsWiX the location of the directory that contains files for this merge module --> <?define SourceDir="..\Deploy"?> <Module Id="DesktopApplicationMM" Language="1033" Version="1.0.0.0"> <Package Id="04cfbb1b-8105-4f3e-9b7a-c1d5354dc670" Manufacturer="DesktopApplicationMM" InstallerVersion="200" /> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="DesktopFolder" /> <Directory Id="MergeRedirectFolder"> <Component Id="owc17DECDE7A34AF545285829FF09EF24AE" Guid="4791fdfe-28ff-3c07-2f9e-e2f418c712f8"> <File Id="owf17DECDE7A34AF545285829FF09EF24AE" Source="$(var.SourceDir)\DesktopApplication.exe" KeyPath="yes"> <Shortcut Id="sc06A337B51AED2DF7E22F894A213D2792" Name="Desktop Application" Directory="DesktopFolder" /> </File> </Component> </Directory> </Directory> <ComponentGroupRef Id="Custom" /> </Module> </Wix> ,左侧为flag

R

怎么可能?

1 个答案:

答案 0 :(得分:1)

这里最明显的解决方案是根据marker-end属性的值将标记设置为marker-startflag

但是,再三考虑一下,我们可以在这里做一些更有趣的事情:我们可以将所有标记设置为marker-end,然后根据flag,我们交换 x1x2属性,使得:

  • x1小于x2(如果标志为R
  • x1x2大(如果标志为L

可以通过以下方式完成:

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>

由于您的值太小,因此我在这里将它们相乘,以便我们更好地看到线条。另外,由于您没有共享任何标记,因此我正在MDN使用该标记。