使用d3js绘制平行测量符号线

我正在尝试向polyline绘制平行线,以便它们看起来像这样:

使用d3js绘制平行测量符号线

我具有绘制折线所需的所有点,但是使用这些点绘制单条线并对其进行平移会使线在两个轴上略微移位,并且这些线也相互连接。我希望它们完全如上图所示。

我正在使用以下代码:

points = [[83.5,144],[172.5,71],[281.5,133],[385.5,77],[437.5,152]];

for (let i = 0; i < points.length; i++) {        
    if (i <= this.points.length - 2) {
        g.append('line')
            .attr('class',"notationLine")
            .attr("x1",points[i][0])
            .attr("y1",points[i][1])
            .attr("x2",points[i+1][0])
            .attr("y2",points[i+1][1])
            .attr("marker-end","url(#arrow)")
            .attr("marker-start","url(#arrowStart)")
            .attr('stroke','#53DBF3')
            .attr('stroke-width',1)
            .attr("transform","translate(-10,-20)");
    }
}
totaleather2009 回答:使用d3js绘制平行测量符号线

您所需要的只是一点三角函数。

例如,给定您设置的距离...

const distance = 15;

...用Math.atan2计算两个点之间的角度,并将其正弦或余弦乘以所需的距离,x位置为正弦,y位置为余弦:

distance * Math.sin(Math.atan(y,x))//for x
distance * Math.cos(Math.atan(y,x))//for y

以下是带有您的数据点的演示:

const points = [
  [83.5,144],[172.5,71],[281.5,133],[385.5,77],[437.5,152]
];

const distance = 15;

const svg = d3.select("svg");

const polyline = svg.append("polyline")
  .attr("points",points.join(" "));

const lines = svg.selectAll(null)
  .data(d3.pairs(points))
  .enter()
  .append("line")
  .attr("x1",d => d[0][0] - (distance * Math.sin(Math.atan2(d[0][1] - d[1][1],d[0][0] - d[1][0]))))
  .attr("x2",d => d[1][0] - (distance * Math.sin(Math.atan2(d[0][1] - d[1][1],d[0][0] - d[1][0]))))
  .attr("y1",d => d[0][1] + (distance * Math.cos(Math.atan2(d[0][1] - d[1][1],d[0][0] - d[1][0]))))
  .attr("y2",d => d[1][1] + (distance * Math.cos(Math.atan2(d[0][1] - d[1][1],d[0][0] - d[1][0]))))
polyline {
  fill: none;
  stroke: blue;
  stroke-width: 2px;
}

line {
  stroke: red;
  stroke-width: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="500" height="200"></svg>

本文链接:https://www.f2er.com/3153495.html

大家都在问