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

问题描述 投票:0回答:1

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

enter image description here

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

我正在使用此代码:

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)");
    }
}
javascript d3.js math svg
1个回答
0
投票
您需要做的是一点三角学。

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

const distance = 15;

...用Math.atan2计算两点之间的角度,并将其正弦或余弦乘以所需的距离,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;
}
© www.soinside.com 2019 - 2024. All rights reserved.