查找 SVG 路径上的点

qia*_*xin 4 javascript d3.js

我用d3js画一条平滑的曲线。然后,我想在曲线上画一个点,但是这个点是随机的,而且我只有x值。我想要获取函数表达式并获取 y 值和 x 值。有什么方法可以得到y值吗?

const line = d3.line()
  .x(d => xScale(new Date(d.name)))
  .y(d => yScale(d.value1))
  .curve(d3.curveCatmullRom);
const series = svg.append('g')
  .attr('transform', `translate(${grid.left},${grid.top})`)
  .append('path')
  .attr('d', line(data))
  .attr('fill', 'transparent')
  .attr('stroke-width', 2)
  .attr('stroke', 'orange');
Run Code Online (Sandbox Code Playgroud)

我当前的图表: 我画电流的图表

Mic*_*sky 5

这是一个在(一种二分搜索)上查找具有指定x坐标的点的函数<path>

注意:路径在X上应该是单调的(路径上不能有2个点具有相同的x)

const findPointAt = (path, x) => {
  let from = 0;
  let to = path.getTotalLength();
  let current = (from + to) / 2;
  let point = path.getPointAtLength(current);
  
  while (Math.abs(point.x - x) > 0.5) {
    if (point.x < x)
      from = current;
    else
      to = current;
    current = (from + to) / 2;
    point = path.getPointAtLength(current);
  }
  return point;
}


const path = d3.select('path').node();

for (let x = 0; x <= 200; x += 50) {
  const pos = findPointAt(path, x);
  console.log(pos);
  d3.select('svg').append('circle')
    .attr('cx', pos.x)
    .attr('cy', pos.y)
    .attr('r', 3)
}
Run Code Online (Sandbox Code Playgroud)
svg {
  border: 1px solid gray;
}

path {
  fill: none;
  stroke: blue;
}

circle {
  fill: red;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<svg width="200" height="150">
  <path d="M 0,10 Q 40,0 90,80 C 120,120 150,70 220,20" /> 
</svg>
Run Code Online (Sandbox Code Playgroud)