从D3线获得一系列积分() [英] Get an array of points from D3 line()

查看:136
本文介绍了从D3线获得一系列积分()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

d3.line(data)返回路径数据字符串。但是,如果我理解正确, d3.line(data).context(context)直接在画布上绘制线条。
如何获得用于在画布上画线的点数

d3.line(data) returns a path data string. But, If I understand correctly, d3.line(data).context(context) draws directly the line on the canvas. How can I get the array of points used to draw the line on the canvas?

并且,是否可以更改 d3.line()。curve()通过传递所需点数得出的线的精确度?

And, is it possible to change the preciseness of the line resulting from d3.line().curve() by passing the number of desired points?

这是我想要实现的目标:

Here is what I want to achieve:

makeACurvedLine([p1, p2, p3], 6)

并从平滑线获得6个点的坐标数组。

And get the array of coordinates of the 6 points from the smoothed line.

实现它的最佳方法是什么?

What is the best way to achieve it?

推荐答案

当你使用 d3时。 line()。context(context)(data)带有画布上下文,它使用canvas的内置函数来绘制圆弧,曲线和其他非线性元素。这意味着d3本身并没有真正减少你用直线连接的一堆点的路径。

When you use d3.line().context(context)(data) with a canvas context, it uses canvas's built-in functions to draw arcs, curves, and other non-linear elements. This means d3 by itself doesn't really reduce your path to a bunch of points it connects with straight lines.

然而,浏览器本身有内置的函数来获取沿着 SVG 路径指向。一种方法是创建一个不可见的svg路径并使用这些函数来计算路径点。对于下面的片段,我将使用均匀间隔的点,但如果某些部分比其他部分更弯曲,您可能需要更精细的东西。

However, the browser itself has built-in functions to get points along an SVG path. One approach is to create an invisible svg path and use those functions to calculate path points. For the following snippet, I'll use uniformly spaced points, though you might want something more refined if there are some parts that are more curvy than others.

var svg = d3.select('body')
  .append('svg')
  .style('display', 'none');

var lineGenerator = d3.line().x(d=>d[0]).y(d=>d[1]).curve(d3.curveNatural);
var path = svg.append('path');

function getLinePoints(curvePoints, numPoints){
  path.attr('d', lineGenerator(curvePoints));
  var svgLine = path.node();
  var lineLength = svgLine.getTotalLength();
  var interval;
  if (numPoints === 1) {
    interval = 0;
  } else {
    interval = lineLength / (numPoints - 1);
  }
  return d3.range(numPoints).map(function (d) {
    var point = svgLine.getPointAtLength(d * interval);
    return [ point.x, point.y ];
  });
};


console.log(getLinePoints([[0,0],[0,10],[20,30]], 6));

<script src="https://d3js.org/d3.v5.min.js"></script>

这篇关于从D3线获得一系列积分()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆