首页 > 解决方案 > 使用 d3js 绘制平行测量符号线

问题描述

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

在此处输入图像描述

我有绘制折线所需的所有点,但是使用这些点来绘制单独的线并平移它们会在两个轴上稍微移动线,并且这些线也相互连接。我想要它们完全如上图所示。

我正在使用这段代码:

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)");
    }
}

标签: javascriptd3.jsmathsvg

解决方案


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

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

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>


推荐阅读