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

标签 javascript d3.js math svg

我正在尝试将平行线绘制到 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)");
    }
}

最佳答案

为此,您只需要一点三 Angular 学知识。

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

const distance = 15;

...您使用 Math.atan2 计算两点之间的 Angular 并将其正弦或余弦乘以您想要的距离,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>

关于javascript - 使用 d3js 绘制平行测量符号线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58727038/

相关文章:

javascript - 将 HTML 控件从一个页面移动到另一页面

math - 在编号系统之间转换

javascript - 如何将 char 添加到 javascript 对象键和值?

javascript - D3 Transform Rescale X向右跳转

javascript - 如何从Nodejs中的内部函数返回值

d3.js - d3 作为 Vue 组件

c# - 生成一个(几乎)具有 30*s²+2 个细胞的六角行星?

database - 在 VB.Net 数据表中查找特定数量的行/列的平均值并存储到数组

javascript - 具有指定高度的 div 内的 Bootstrap 3 Css 文本

javascript - 如何在 JavaScript 中引用原始类型?